栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C# > C#教程

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

C#教程 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

详解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# 路径访问被拒绝内容请搜索考高分网以前的文章或继续浏览下面的相关文章希望大家以后多多支持考高分网!

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/121544.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号