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

2022-07-25,,,,

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

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

下载本文的Word格式文档,以方便收藏与打印。