我该如何解决这个问题? "A first chance exception of type 'System.IO.IOException' occurred in mscorlib.dll"

How can I solve this? "A first chance exception of type 'System.IO.IOException' occurred in mscorlib.dll"

我最近开始使用 Visual C#,因为我认为尝试一次不同于 Unity 的东西会很有趣。所以我尝试制作一个程序,搜索设置的目录,根据我需要的扩展名抓取文件,然后将它们移动到一个文件夹中。

现在我已经找到目录扫描并过滤掉所有我需要使用 DirectoryInfo 和 FileInfo 列表的扩展,这不会导致任何明显的问题。 FileInfo.MoveTo 方法让我很生气。我设置了一个字符串变量,您将在下面看到它作为路径。然后将其作为 MoveTo 的字符串参数。一切似乎都有意义,当我把文件移动到根目录时,当我把 "target.Name" 放在它时它会工作,但如果我把 "Directory.GetCurrentDirectory()" 或 "target.Name" 以外的任何其他目录都不会工作因为它本身。

很抱歉这个冗长的问题,但这真的让我很生气。

static List<FileInfo> _targetFiles = new List<FileInfo>();
static string _targetPath = Directory.GetCurrentDirectory();
 static void Main(string[] args)
    {


        CopyFiles(_targetFiles, _targetPath);
        Console.WriteLine("Scan finished.");
        Console.Read();
    }
static void CopyFiles(List<FileInfo> files, string path)
    {
        foreach (FileInfo target in files)
        {
            try
            {

                target.MoveTo(_targetPath);
                Console.ForegroundColor = ConsoleColor.Green;
                Console.WriteLine(target + " moved to " + _targetPath);
                Console.ResetColor();

            }
            catch
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("TRANSFER FAILED: " + target);
                Console.ResetColor();
            }

        }
    }

输出:

A first chance exception of type 'System.IO.IOException' occurred in mscorlib.dll

控制台

TRANSFER FAILED: filename.ext

不确定我是否正确回答了问题。当您使用当前目录 (Directory.GetCurrentDirectory();) 时,您似乎正试图覆盖您的 exe 和 dll。

其次,您需要提供一个完全限定的路径作为文件名。目录路径映射到文件夹。