詳解C#對路徑...的訪問被拒絕解決過程
用C#想寫一個直接將數據庫查詢得到的datatable,直接導出為csv格式的文件,拷貝到導出的操作類后,一直catch到的錯誤提示是對路徑的泛微被拒絕,一直排查原因,發現原來:FileStream(path, FileMode.OpenOrCreate,FileAccess.ReadWrite),path處所讀取的字符串必須包含文件名稱以及格式。現在貼完整代碼,以供幫助到像我一樣的初學者。
private void button1_Click(object sender, EventArgs e) { System.IO.StreamReader st; //由于我的查詢語句較長,采用了讀取txt文本的方式后做查詢操作。 st = new System.IO.StreamReader(Application.StartupPath + "\\SQL2.txt", System.Text.Encoding.Default); string stingsql=st.ReadToEnd(); st.Close(); textBox1.Text = stingsql; DataTable dt = new DataTable(); dt = bc.QueryCommand(stingsql); string filepath = @"F:\病案導出備份\患者統計表.csv";//此處必須為路徑加文件名稱,否則 ImportToCSV(dt, filepath); } public static void ImportToCSV(DataTable dt, string filepath) { FileStream fs = null; StreamWriter sw = null; try { fs = new FileStream(filepath, FileMode.Create, FileAccess.Write); sw = new StreamWriter(fs, Encoding.Default); string head = ""; //拼接列頭 for (int cNum = 0; cNum < dt.Columns.Count; cNum++) { head += dt.Columns[cNum].ColumnName + ","; } //csv文件寫入列頭 sw.WriteLine(head); string data = ""; //csv寫入數據 for (int i = 0; i < dt.Rows.Count; i++) { string data2 = string.Empty; //拼接行數據 for (int cNum1 = 0; cNum1 < dt.Columns.Count; cNum1++) { data2 = data2 + "\"" + dt.Rows[i][dt.Columns[cNum1].ColumnName].ToString() + "\","; } bool flag = data != data2; if (flag) { sw.WriteLine(data2); } data = data2; } string msg = "數據被成功導出到:" + filepath; MessageBox.Show(msg); } catch (Exception ex) { // logger.Error("導出csv失敗!" + ex.Message); MessageBox.Show("導出失敗" + ex.Message); return; } finally { if (sw != null) { sw.Close(); } if (fs != null) { fs.Close(); } sw = null; fs = null; } }
示例2
問題代碼:
private bool GetChannelInfo() { comCheckWindow.LoadCheckResult("準備加載項目通道信息", Color.FromName("Green")); XmlDocument proFile = new XmlDocument(); //讀取項目配置文件 proFile.Load(proFilePath); XmlNodeList channelList = proFile.SelectSingleNode("Project").ChildNodes; if (channelList.Count == 0) return false; ...... return true; }
在“proFile.Load(proFilePath)”語句處發生錯誤,提示對路徑…(proFilePath的值)的訪問被拒絕。
嘗試過將目標文件重新選擇路徑(從C盤轉移到D盤),或提升程序運行權限(在以管理員身份運行Visual Studio的情況下打開項目文件),均無效。
最后檢查程序時發現:路徑proFilePath的值不正確,運行“proFile.Load(proFilePath)”要求路徑proFilePath指向一個確定的XML文件,但此處路徑的值為該XML文件所在目錄的路徑,由于Load函數的參數指向對象類型不匹配,從而導致出錯。
到此這篇關于詳解C#對路徑...的訪問被拒絕解決過程的文章就介紹到這了,更多相關C# 路徑訪問被拒絕內容請搜索腳本之家以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Datagridview使用技巧(9)Datagridview的右鍵菜單
這篇文章主要為大家詳細介紹了Datagridview使用技巧,Datagridview的右鍵菜單,具有一定的參考價值,感興趣的小伙伴們可以參考一下2017-05-05
最新評論