Using file.move to rename new files in C#

梦想与她 提交于 2019-12-02 03:55:11

There are a few problems with your code.

First, you should use e.FullPath instead of e.Name, otherwise the code will try to rename the file in the current directory, instead of watched directory.

Second, to receive Created event you should include NotifyFilters.FileName.

However, this will not help you much, because the file is locked in the created and changed events until the file is copied, so you'll get an exception. Also, you'll probably receive more than one Changed event (in my tests I always receive two, regardless of the file size, but it may be different on the different versions of Windows or .Net framework).

To fix this, you may use timers or threads to accomplish the task. Here's an example using ThreadPool thread. Whenever created is fired, you create a new thread. In the thread you check whether a file is locked (trying to open file), and when the file is unlocked, do the rename.

public class FileMon
{
    public static void Run()
    {
        FileSystemWatcher fsWatcher = new FileSystemWatcher();
        fsWatcher.Path = @"C:\Test\";        
        fsWatcher.Filter = "*.*" ;
        fsWatcher.IncludeSubdirectories = true;

        // Monitor all changes specified in the NotifyFilters.
        fsWatcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.FileName ;

        fsWatcher.EnableRaisingEvents = true;

        // Raise Event handlers.
        fsWatcher.Changed += OnChanged;
        fsWatcher.Created += OnCreated;
        Console.WriteLine("[Enter] to end"); Console.ReadLine();
        fsWatcher.EnableRaisingEvents = false;
    }

    static void Worker(object state)
    {
        FileSystemEventArgs fsArgs = state as FileSystemEventArgs;
        bool done = false;
        FileInfo fi = new FileInfo(fsArgs.FullPath);

        do
        {
            try
            {
                using (File.Open(fsArgs.FullPath, FileMode.Open))
                {
                    done = true;
                }
            }
            catch
            {
                done = false;
            }
            Thread.Sleep(1000);
        } while (!done);
        Console.WriteLine("DOne");
        string dateStamp = DateTime.Now.ToString("fff");
        string fName = fi.FullName;
        string newFile = fsArgs.FullPath + dateStamp;
        File.Move(fsArgs.FullPath, newFile);
    }

    private static void OnCreated(object sender, FileSystemEventArgs e)
    {
        Console.WriteLine($"Created {e.ChangeType} : {e.Name}");
        ThreadPool.QueueUserWorkItem(Worker, e);
    }

    static void OnChanged(object sender, FileSystemEventArgs e)
    {
        Console.WriteLine($"{e.ChangeType} : {e.FullPath}");
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!