简体   繁体   中英

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. Now i want to validate in C# whether the .txt file has come or not in this path. 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?

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. 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. Hope it helps.

To get the .txt file only Please use below code. It will get you the latest txt file.

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 。文本”;

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