文件正被另一个进程使用 StreamWriter 使用

Chr*_*tig 5 c# streamwriter

我的程序对我来说是练习,但是,当我尝试写入它找到的所有目录时,它崩溃了。

我尝试了以下方法:

  • 让它写入文件流而不是文件本身
  • 使用 File.Writealllines 使用 list<> (这有效,只是它完成了前五个,不再有)
  • FileStream.Write(subdir.ToCharArray())

我不明白为什么这不起作用,我做错了什么?

static void Main(string[] args)
{
    Method(@"C:\");
}

static void Method(string dir)
{
    //crash happens here v
    StreamWriter sw = new StreamWriter(@"C:\users\"+Environment.UserName+"\desktop\log.txt",true);

    foreach (string subdir in Directory.GetDirectories(dir))
    {
        try
        {
            Console.WriteLine(subdir);
            sw.Write(subdir);
            Method(subdir);
        }
        catch (UnauthorizedAccessException)
        {
            Console.WriteLine("Error");
        }
    }
  sw.Close(); 
}
Run Code Online (Sandbox Code Playgroud)

Sim*_*ead 4

它是递归的。

因为你Method又在这里打电话:

Console.WriteLine(subdir);
sw.Write(subdir);
Method(subdir); // BOOM
Run Code Online (Sandbox Code Playgroud)

您的文件已经打开。您无法再次打开它进行写入。

一次打开文件Main..

static void Main(string[] args) {
    using (StreamWriter sw = new StreamWriter(@"C:\users\"+Environment.UserName+"\desktop\log.txt",true)) {
        Method(@"C:\", sw);
    }
}
Run Code Online (Sandbox Code Playgroud)

然后在您的方法中接受它:

public static void Method(string dir, StreamWriter sw) {
Run Code Online (Sandbox Code Playgroud)

然后当你再次调用它时:

sw.Write(subdir);
Method(subdir, sw); // pass in the streamwriter.
Run Code Online (Sandbox Code Playgroud)

但请注意,您很快就会开始消耗内存。您正在递归整个 C:\ 驱动器。也许在较小的文件夹上测试它?