详解C#对路径...的访问被拒绝解决过程

这篇文章主要介绍了详解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 

示例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#对路径...的访问被拒绝解决过程的详细内容,更多请关注0133技术站其它相关文章!

赞(0) 打赏
未经允许不得转载:0133技术站首页 » 其他教程