c# - 等待文件存在于目录 C#

标签 c# directory file-exists visual-c#-express-2010

我正在创建一个 Visual C# 应用程序,它的部分功能是在 .gz 文件出现在目录中时将其提取出来。一旦执行命令行参数,.gz 文件就会出现在指定的目录中。

不幸的是,我收到一条错误消息,提示“找不到此文件”,这是因为它读取提取 .gz 文件的行太快了。

换句话说,它试图在命令行参数执行之前执行一个 .gz 文件,并将文件实际放入目录中。

我想找到一种方法让我的程序在继续读取下一行之前等待文件出现在目录中。

下面是我的代码,任何帮助将不胜感激!谢谢!

else if (ddlDateType.Text == "Monthly" || ddlDateType.Text == "")
{
    //Check if Monthly date entered is valid
    if (DateTime.TryParseExact(txtDate.Text, MonthlyFormat, null,
        System.Globalization.DateTimeStyles.None, out Test) != true)
    {
        MessageBox.Show("Enter a valid date.\nFormat: yyyyMM");
    }
    else
    {
        //Method that executes an arugment into the command prompt
        ExecuteCommand();

        //Method that extracts the file after it has already appeared in the directory
        ExtractFile();

        /*
        Goal is to wait for the file to appear in the directory before it executes
        the ExtractFile() method.
         */

    }
}

最佳答案

您可以使用 FileSystemWatcher。 https://msdn.microsoft.com/it-it/library/system.io.filesystemwatcher(v=vs.110).aspx

在此示例中,每次将文件添加到受监控的文件夹时都会调用回调 OnChanged。

   [PermissionSet(SecurityAction.Demand, Name="FullTrust")]
    public static void RunWathcer()
    {

        // Create a new FileSystemWatcher and set its properties.
        FileSystemWatcher watcher = new FileSystemWatcher();

        watcher.Path = "PATH TO WATCH GOES HERE!!";

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

        watcher.Filter = "*.*";

        watcher.Created += new FileSystemEventHandler(OnChanged);
        watcher.EnableRaisingEvents = true;
    }

    // Define the event handlers.
    private static void OnChanged(object source, FileSystemEventArgs e)
    {
        // Specify what is done when a file is changed, created, or deleted.
       Console.WriteLine("File: " +  e.FullPath + " " + e.ChangeType);
    }
}

关于c# - 等待文件存在于目录 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38000264/

相关文章:

c# - 如何将 20 个 100mb CSV 文件批量插入 SQL Server

c# - 如何创建磁贴系统

Linux无法进入目录

php - 如何使用phpseclib通过SFTP检查上传的文件是否存在

php - file_exists() 用于文件名中包含 (&) 的文件

c# - 此示例代码中是否需要“异步/等待”?

c# - 如何在 ASP.NET MVC 中路由 Web 表单页面?

java - Wicket 口目录结构

python - 路径内文件夹内文件内的深度小写

Python - 如何在 Ubuntu 上的根文件夹中打开或创建文件?