Hap*_*NET 3 c# asp.net text-files
我正在尝试使用以下代码创建并写入C#应用程序中的文本文件
System.IO.Directory.CreateDirectory(Server.MapPath("~\\count"));
using (System.IO.FileStream fs = new System.IO.FileStream("~/count/count.txt", System.IO.FileMode.Create))
using (System.IO.StreamWriter sw = new System.IO.StreamWriter("~/count/count.txt"))
{
sw.Write("101");
}
string _count = System.IO.File.ReadAllText("~/count/count.txt");
Application["NoOfVisitors"] = _count;
Run Code Online (Sandbox Code Playgroud)
但是我收到一个错误:
该进程无法访问文件"路径",因为它正由另一个进程使用.
我的错误是什么?
你试图打开文件两次; 您的第一个using语句会创建一个FileStream未使用的语句,但会锁定该文件,因此第二个语句会using失败.
只需删除你的第一using行,它应该都可以正常工作.
但是,我建议更换所有这些File.WriteAllText,然后在你的代码中没有使用,它会更简单.
var dir = Server.MapPath("~\\count");
var file = Path.Combine(dir, "count.txt");
Directory.CreateDirectory(dir);
File.WriteAllText(file, "101");
var _count = File.ReadAllText(file);
Application["NoOfVisitors"] = _count;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20191 次 |
| 最近记录: |