//检查文件,如果文件不存在则创建 private void ExistsFile(string FilePath) { //if(!File.Exists(FilePath)) //File.Create(FilePath); //以上写法会报错,详细解释请看下文......... if (!File.Exists(FilePath)) { FileStream fs = File.Create(FilePath); fs.Close(); } } private void Button2_Click(object sender, System.EventArgs e) { ExistsFile(Server.MapPath("test/weather.txt"));//检查文件是否存在 //读取文件 StreamReader sr = new StreamReader(Server.MapPath("test/weather.txt"), System.Text.Encoding.Default); try { string input = sr.ReadToEnd(); sr.Close();
错误解释:
//当在指定路径没有文件的时候
//最初的方法:最开始调用
if (!File.Exists(filePath))
{
File.Create(filePath);
}
//在进行读写操作的时候:
private void Button2_Click(object sender, System.EventArgs e)
{
ExistsFile(Server.MapPath("test/weather.txt"));//检查文件是否存在
//读取文件
StreamReader sr = new StreamReader(Server.MapPath("test/weather.txt"), System.Text.Encoding.Default);
try
{
string input = sr.ReadToEnd();
sr.Close();
input = input.Replace("\r\n", "").Replace("\n", "");
this.TextBox1.Text = input;
}
catch
{
Response.Write("<script>alert('文件读取失败');</script>");
}
}
//就会出现“文件写的时候,正由另一进程使用,因此该进程无法访问该文件”
//分析问题是原因是:File.Create(FilePath); 创建了文件,进程没有结束
//所以该用流创建文件
if (!File.Exists(filePath))
{
FileStream fs1 = File.Create(filePath);
fs1.Close();
}
//当流创建文件后,关闭流,就不会出现类似的问题了.....