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

  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;

  }

  }