你为什么要这么做?
using (StreamWriter sw = File.CreateText(path))
{
for (int i = 0; i < 100; i++)
{
sw.WriteLine(i.ToString());
}
int count = File.ReadLines(path).Count();
sw.WriteLine(count.ToString());
}
我收到此错误消息:&#34;该进程无法访问该文件,因为该文件被另一个进程使用。&#34;
所以我觉得我必须这样说:
using (StreamWriter sw = File.CreateText(path))
{
for (int i = 0; i < 100; i++)
{
sw.WriteLine(i.ToString());
}
}
using (StreamWriter sw = File.CreateText(path))
{
int count = File.ReadLines(path).Count();
sw.WriteLine(count.ToString());
}
但我得到同样的错误。我对此很糟糕,有人请帮帮我:)。
答案 0 :(得分:3)
当您致电ReadLines()
时,由于打开StreamWriter
,该文件已经打开。
您必须按顺序执行操作:
int count = File.ReadLines(path).Count();
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine(count.ToString());
}
答案 1 :(得分:0)
using (StreamWriter sw = File.CreateText(path))
{
for (int i = 0; i < 100; i++)
{
sw.WriteLine(i.ToString());
}
}
int count = File.ReadLines(path).Count();
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine(count.ToString());
}