我的程序对我来说是练习,但是,当我尝试写入它找到的所有目录时,它崩溃了。
我尝试了以下方法:
我不明白为什么这不起作用,我做错了什么?
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)
它是递归的。
因为你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:\ 驱动器。也许在较小的文件夹上测试它?
| 归档时间: |
|
| 查看次数: |
21763 次 |
| 最近记录: |