简体   繁体   English

如何在C#中检查文本文件是否已在特定路径中生成

[英]How to check if a text file has generated in a particular path or not in C#

one .txt file is getting exported inside the path - D:\\work\\int\\retail\\store\\export after i run a Stored procedure. 运行存储过程后,一个.txt文件正在路径内导出-D:\\ work \\ int \\ retail \\ store \\ export。 Now i want to validate in C# whether the .txt file has come or not in this path. 现在我想在C#中验证.txt文件是否在此路径中。 I am using the below syntax according to which file.exists() is still returning false even though .txt file is there in the export location.what's going wrong here?Any help will be appreciated on this.how can i get the latest file name coming in this location dynamically and pass to this below query? 我正在使用以下语法,即使出口位置上有.txt文件,file.exists()仍返回false。这里出了什么问题?对此我们将提供任何帮助。如何获取最新文件名称动态地进入此位置并传递给下面的查询?

var FilePath = @"D:\work\int\retail\store\export";
            if(File.Exists(FilePath))
            {
                //do this
            }

for checking if specific files exists on a path use File.Exists(path), which will return a boolean indicating whether the file at path exists. 要检查路径上是否存在特定文件,请使用File.Exists(path),它将返回一个布尔值,指示路径中的文件是否存在。 In your case 就你而言

if(File.Exists(@"D:\work\int\retail\store\export\one.txt"))
{
    //do this
}

In your example you are missing the filename. 在您的示例中,您缺少文件名。

If you want to fetch the latest file from some directory use this code. 如果要从某个目录中获取最新文件,请使用此代码。

    var directory = new DirectoryInfo(@"D:\work\int\retail\store\export");
    var File = directory.GetFiles()
                 .OrderByDescending(f => f.LastWriteTime)
                 .First();

You have to create a variavble of DirectoryInfo Class which takes directory path as parameter, Here I have passed your directory path D:\\work\\int\\retail\\store\\export , Now GetFiles() function returns all the files inside the directory and I have sorted them in Descending order by LastWriteTime property of files, and fetched the first file which will be the latest file in the directory. 您必须创建一个以目录路径作为参数的DirectoryInfo类的变量,在这里,我传递了您的目录路径D:\\work\\int\\retail\\store\\export ,现在GetFiles()函数返回目录中的所有文件,而我已按照文件的LastWriteTime属性以降序对它们进行了排序,并获取了第一个文件,该文件将是目录中的最新文件。 Hope it helps. 希望能帮助到你。

To get the .txt file only Please use below code. 仅获取.txt文件,请使用以下代码。 It will get you the latest txt file. 它将为您获取最新的txt文件。

var directory = new DirectoryInfo(@"C:\Users\Saket\Downloads\");
var File = directory.GetFiles().Where(c=>c.Extension == ".txt")
                         .OrderByDescending(f => f.LastWriteTime)                         
                         .First();

您需要在路径中提及您的文本文件名,例如,如果您的txt文件名为x.txt,则需要将路径写为var FilePath = @“ D:\\ work \\ int \\ retail \\ store \\ export \\ x 。文本”;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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