在C#中通過cmd.exe調用GDAL工具實現特定功能

我們在C#中使用GDAL時,某些功能並不能像C++那樣應有盡有,甚至還不如Python那麼好用,因此要實現某些特定功能,可能就要迫不得已地通過cmd.exe調用GDAL工具,下以調用gdalwarp.exe爲例,爲正在C#中使用GDAL開發同行提供有益的參考。

System.Diagnostics.Process process = new System.Diagnostics.Process();
process.StartInfo.FileName = "cmd.exe";
process.StartInfo.UseShellExecute = false;//是否使用操作系統shell啓動
process.StartInfo.RedirectStandardInput = true;//接受來自調用程序的輸入信息
process.StartInfo.RedirectStandardOutput = true;//由調用程序獲取輸出信息
process.StartInfo.RedirectStandardError = true;//重定向標準錯誤輸出
process.StartInfo.CreateNoWindow = true;
process.Start();//啓動程序
 //獲取gdalward.exe路徑,我這裏是與dll放在一起,方便其調用相關dll
var executingAssemblyFile = new Uri(Assembly.GetExecutingAssembly().GetName().CodeBase).LocalPath;
var executingDirectory = Path.GetDirectoryName(executingAssemblyFile);
var gdalPath = Path.Combine(executingDirectory, "gdal");
var nativePath = Path.Combine(gdalPath, IntPtr.Size == 4 ? "x86" : "x64");
//image registration:first order geometric polynomial
//路徑、參考系(字符串)和文件名等均加了雙引號,具體可以百度why
 string strCMD = "\"" + nativePath + "\\gdalwarp.exe" + "\"" + " -t_srs \"" + strTargetWkt +
                                 "\" -order 1 -r cubicspline -tr " + Convert.ToString(GeoTransform[1]) 
                                 + " " + Convert.ToString(GeoTransform[5]) + " \"" + strTempFile 
                                 +  "\" \"" + targetFileName + "\"";
process.StandardInput.WriteLine(strCMD+"&exit");
process.StandardInput.AutoFlush = true;
//string outPut = process.StandardOutput.ReadToEnd();//獲取cmd窗口的輸出信息
process.WaitForExit();//等待程序執行完退出進程
process.Close();
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章