未处理的异常:System.IO.IOException:进程无法访问文件

问题描述

我不确定如何解决此错误。

更新

Zen's solution解决了LogFile\FWLog.txt文件已经存在的错误,但是当LogFile\FWLot.txt不存在时错误仍然存​​在。

未处理的异常:System.IO.IOException:该进程无法访问文件'C:\ Users \ user \ OneDrive \ CodeWorkspace \ NET \ fw \ fw \ LogFile \ FWLog.txt',因为该文件正在被另一个进程使用

在System.IO .__ Error.WinIOError(Int32 errorCode,可能是StringFullPath)
在System.IO.FileStream.Init(字符串路径,FileMode模式,FileAccess访问,Int32权限,布尔useRights,FileShare共享,Int32 bufferSize,FileOptions选项,SECURITY_ATTRIBUTES secAttrs,字符串msgPath,布尔bFromProxy,布尔useLongPath,布尔checkHost) /> 在System.IO.FileStream..ctor中(字符串路径,FileMode模式,FileAccess访问,FileShare共享,Int32 bufferSize,FileOptions选项,String msgPath,布尔bFromProxy,布尔useLongPath,布尔checkHost)
在System.IO.File.InternalReadAllBytes(字符串路径,布尔值CheckHost)
在FW.CreateLog(String logName,String path,DateTime time)
在FW.Watch(字符串路径) 在FW.Run()
在FW.Main()

代码:

using System;
using System.IO;

public class FW
{
    private static StreamWriter log;
    public static void Main()
    {
        Run();
    }

    private static void Run()
    {
        string option = "";
        Console.WriteLine("File System Watcher\nThis program monitors activity in a specified directory.");
        string[] args = Environment.GetCommandLineArgs();
        if (args.Length >= 2)
        {
            String path = args[1];
            Watch(path);
        }
        while (!option.Equals("3"))
        {
            do
            {
                Console.Write("Choose an option:\n[1] Monitor a direcotry.\n[2] Open log history\n[3] Quit\n>> ");
                option = Console.ReadLine();
            } while (!option.Equals("1") && !option.Equals("2") && !option.Equals("3"));
            switch (option)
            {
                case "1":
                    Watch("");
                    break;
                case "2":
                    if ((Directory.Exists("LogFile") && !File.Exists("LogFile\\FWLog.txt")) || !Directory.Exists("LogFile"))
                    {
                        Console.WriteLine("There are no saved logs.");
                    }
                    else
                    {
                        Console.WriteLine("\nLog History");
                        DumpLog("LogFile\\FWLog.txt");
                    }
                    break;
            }
        }
        Console.WriteLine("Quiting...");
    }

    //[PermissionSet(SecurityAction.Demand,Name = "FullTrust")]
    private static void Watch(string path)
    {
        DateTime time = DateTime.Now;
        string logName = "LogFile\\FWLog.txt";
        while (!Directory.Exists(path))
        {
            Console.Write("Please enter a valid absolute directory path (i.e. C:\\Users\\john\\Documents)\n>> ");
            path = Console.ReadLine();
        }
        Console.WriteLine("Monitoring: " + path);
        CreateLog(logName,path,time);
        log = File.AppendText(logName);
        // Create a new FileSystemWatcher and set its properties.
        using (FileSystemWatcher watcher = new FileSystemWatcher())
        {
            watcher.IncludeSubdirectories = true;
            watcher.Path = path;

            // Watch for changes in LastAccess and LastWrite times,and
            // the renaming of files or directories.
            watcher.NotifyFilter = NotifyFilters.LastWrite
                                 | NotifyFilters.FileName
                                 | NotifyFilters.DirectoryName;

            // Add event handlers.
            watcher.Changed += OnChanged;
            watcher.Created += OnChanged;
            watcher.Deleted += OnChanged;
            watcher.Renamed += OnRenamed;

            // Begin watching.
            watcher.EnableRaisingEvents = true;

            // Wait for the user to quit the program.
            Console.WriteLine("Press 'q' to stop monitoring.");
            while (!(Console.ReadLine()).Equals("q")) ;
        }
        log.Close();
    }
    // Define the event handlers.
    private static void OnChanged(object source,FileSystemEventArgs e)
    {
        string status = $"{Path.GetFileName(e.FullPath)} in {Path.GetDirectoryName(e.FullPath)} {e.ChangeType} {DateTime.Now}";
        // Specify what is done when a file is changed,created,or deleted.
        if ((e.FullPath).Contains("LogFile\\FWLog.txt"))
        {
            return;
        }
        else
        {
            Console.WriteLine(status);
            log.WriteLine(status);
        }
    }

    private static void OnRenamed(object source,RenamedEventArgs e)
    {
        string status = $"{Path.GetFileName(e.OldFullPath)} Renamed to {Path.GetFileName(e.FullPath)} in {Path.GetDirectoryName(e.FullPath)} {DateTime.Now}";
        // Specify what is done when a file is renamed.
        Console.WriteLine(status);
        log.WriteLine(status);
    }

    private static void CreateLog(string logName,string path,DateTime time)
    {
        if (!Directory.Exists("LogFile"))
            Directory.CreateDirectory("LogFile");
        if (!File.Exists(logName))
            File.Create(logName);
        using (StreamWriter logCreate = File.AppendText(logName))
        {
            if (File.ReadAllBytes(logName).Length == 0)
            {
                logCreate.WriteLine($"Monitored: {path} {time}");
            }
            else
            {
                logCreate.WriteLine($"\nMonitored: {path} {time}");
            }
            logCreate.Close();
        }
    }

    private static void DumpLog(string logFile)
    {
        string line;
        if (File.ReadAllBytes(logFile).Length == 0)
        {
            Console.WriteLine("Log file is empty.");
        }
        else
        {
            using (StreamReader r = File.OpenText(logFile))
            {
                while ((line = r.ReadLine()) != null)
                {
                    Console.WriteLine(line);
                }
                Console.WriteLine();
            }
        }
    }
}

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)