简体   繁体   中英

C# problem with file.exist statement in if else statement

I'm currently doing a school project where the program uses filesystemwatcher to watch a file and copy to other folders when a file is detected. However whenever there is an update to the file it will save it as _update.txt appended to the back with a copy() function I made.

The problem is there are at times where the program renames it as update even though it's the first instance of the file. Copy function works fine. Really appreciate it as I'm a programming newbie!!

Codes are as follows:

try
{
    String dest = "inputTextBox.text" + "\\";
    String fileName = e.Name;

    if (!File.Exist(dest + fileName))
    {
        try
        {
            copy("");
        }

        catch(Exception e) 
        {
            return;
        }
    }

    else if (File.Exist(dest + fileName))
    {
        try
        {
            copy("update.txt");
        }

        catch(Exception e)
        {
            return;
        }
    }
}
catch (Exception e)
{
    return;
}

I think you should use FileSystemWatcher for your task. Set Filter to your filename and subscribe for Created event.

For example:

static void Main(string[] args)
{
    var watcher = new FileSystemWatcher //
    {
        Path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), //Set watching to MyDocuments folder
        InternalBufferSize = 32 * 1024, // set 32KB buffer size (it's a maximal size)
        Filter = "*", //Set filter to all file types
        NotifyFilter = NotifyFilters.FileName, //We need this notify type for watch creating files
        EnableRaisingEvents = true //Begin watcing
    };
    watcher.Created += (s, e) => //subscribe lambda to "created" event
    {
        Console.WriteLine($"{e.FullPath} created");
        Task.Delay(1000).Wait();
        try
        {
            File.Copy(e.FullPath, Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), "updated", $"{e.Name}-{Guid.NewGuid()}"));
        }
        catch(Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    };
    Console.ReadLine(); //waiting
}

I tested this code in a console application. When the application is running, try creating a file in the MyDocuments folder. The program will send a message about creating the files and copy them file in "updated" folder.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM