软件编程
位置:首页>> 软件编程>> C#编程>> 详解C#对路径...的访问被拒绝解决过程

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

作者:Mr.Emiya  发布时间:2021-06-01 11:12:10 

标签: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函数的参数指向对象类型不匹配,从而导致出错。

来源:https://blog.csdn.net/Melody1994/article/details/93162637

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com