詳解C#對路徑...的訪問被拒絕解決過程
用C#想寫一個直接將數(shù)據(jù)庫查詢得到的datatable,直接導(dǎo)出為csv格式的文件,拷貝到導(dǎo)出的操作類后,一直catch到的錯誤提示是對路徑的泛微被拒絕,一直排查原因,發(fā)現(xiàn)原來:FileStream(path, FileMode.OpenOrCreate,FileAccess.ReadWrite),path處所讀取的字符串必須包含文件名稱以及格式。現(xiàn)在貼完整代碼,以供幫助到像我一樣的初學者。
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:\病案導(dǎo)出備份\患者統(tǒng)計表.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寫入數(shù)據(jù) for (int i = 0; i < dt.Rows.Count; i++) { string data2 = string.Empty; //拼接行數(shù)據(jù) 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 = "數(shù)據(jù)被成功導(dǎo)出到:" + filepath; MessageBox.Show(msg); } catch (Exception ex) { // logger.Error("導(dǎo)出csv失??!" + ex.Message); MessageBox.Show("導(dǎo)出失敗" + 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)”語句處發(fā)生錯誤,提示對路徑…(proFilePath的值)的訪問被拒絕。
嘗試過將目標文件重新選擇路徑(從C盤轉(zhuǎn)移到D盤),或提升程序運行權(quán)限(在以管理員身份運行Visual Studio的情況下打開項目文件),均無效。
最后檢查程序時發(fā)現(xiàn):路徑proFilePath的值不正確,運行“proFile.Load(proFilePath)”要求路徑proFilePath指向一個確定的XML文件,但此處路徑的值為該XML文件所在目錄的路徑,由于Load函數(shù)的參數(shù)指向?qū)ο箢愋筒黄ヅ洌瑥亩鴮?dǎo)致出錯。
到此這篇關(guān)于詳解C#對路徑...的訪問被拒絕解決過程的文章就介紹到這了,更多相關(guān)C# 路徑訪問被拒絕內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
C#程序終極調(diào)試實現(xiàn)windbg的時間旅行
這篇文章主要介紹了C#程序終極調(diào)試實現(xiàn)windbg的時間旅行示例詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2022-06-06C#創(chuàng)建WebService接口并連接的全過程
工作時遇到需要請求客戶的接口返回數(shù)據(jù),要求使用WebService,借此機會記錄一下,下面這篇文章主要給大家介紹了關(guān)于C#創(chuàng)建WebService接口并連接的相關(guān)資料,文中通過示例代碼介紹的非常詳細,需要的朋友可以參考下2022-12-12