详解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 + "\\", 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# 路径访问被拒绝内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论