How to check any .txt file exists in a folder? [duplicate] - c#

This question already has answers here:
Find a file with a certain extension in folder
(6 answers)
Closed 7 years ago.
How to check if any .txt file exists in a folder?
If the folder still have .txt file output a error messagebox.
Thx all! Actually i want to make a function can check any .txt file exists in a folder. If yes write a error message to eventLog.
Final My code:
System.Diagnostics.EventLog appLog = new System.Diagnostics.EventLog();
DirectoryInfo di = new DirectoryInfo(#"c:/Users/Public/Definitions");
FileInfo[] TXTFiles = di.GetFiles("*.txt");
foreach (var fi in TXTFiles)
{
if (fi.Exists)
{
appLog.Source = "Definitions Folder still have text files";
appLog.WriteEntry("Still have txt files.");
}
}

You can check like below :
DirectoryInfo dir = new DirectoryInfo(#"c:\Directory");
FileInfo[] TXTFiles = dir.GetFiles("*.txt");
if (TXTFiles.Length == 0)
{
//No files present
}
foreach (var file in TXTFiles)
{
if(file.Exists)
{
//.txt File exists
}
}

You can use the Directory.EnumerateFiles like this:
if(Directory.EnumerateFiles(folder, "*.txt",SearchOption.TopDirectoryOnly).Any())
Foo();
See more here Directory.EnumerateFiles Method

You can do it like this
string[] files = System.IO.Directory.GetFiles(path, "*.txt");
if(files.Length >= 1)
{
MessageBox.Show("Error Message ... Your folder still have some Txt files left");
// or
Console.WriteLine("Error Message ... Your folder still have some Txt files left");
}

Related

Get all filenames from project folder [duplicate]

This question already has answers here:
Get a list of all resources from an assembly
(2 answers)
Closed 7 days ago.
I have some files in a "FileFolder" folder in a project. Path to this folder:
pack://application:,,,/MyProject;Component/FileFolder/
All files in the "Build action" property are set to "Resource".
How to get a list of filenames from code?
This code might work.
DirectoryInfo directoryInfo = new DirectoryInfo("YOUR PATH");
FileInfo[] files = directoryInfo.GetFiles();
foreach (FileInfo fileInfo in files)
{
richTextBox1.Text += fileInfo.Name + "\n";
}

Adding folder files into a listbox [duplicate]

How can I list the text files in a certain directory (C:\Users\Ece\Documents\Testings) in a listbox of a WinForm(Windows application)?
// What directory are the files in?...
DirectoryInfo dinfo = new DirectoryInfo(#"C:\TestDirectory");
// What type of file do we want?...
FileInfo[] Files = dinfo.GetFiles("*.txt");
// Iterate through each file, displaying only the name inside the listbox...
foreach( FileInfo file in Files )
{
listbox1.Items.Add(file.Name);
}
// A statement, followed by a smiley face...
That oughta do it. ;o)
To get the txt files, try this:
var folder = #"C:\Users\Ece\Documents\Testings";
var txtFiles = Directory.GetFiles(folder, "*.txt");
listBox.Items.AddRange(txtFiles);

Delete all files in a web directory

I have a web directory that contains files and I want to delete them all. I've looked online but all the answers rely on the file system and I want to use the website's directories. I tried this:
foreach (string file in HttpContext.Current.Server.MapPath("\\MyDirectory"))
{
File.Delete(file);
}
The foreach statement is underlined and the error is 'cannot convert type char to string'.
What's the syntax to delete all files in a directory?
Your might need to correct your MapPath parameter (\\MyDirectory), but the syntax you need is shown below.
System.IO.DirectoryInfo di= new DirectoryInfo(HttpContext.Current.Server.MapPath("\\MyDirectory"));
foreach (FileInfo file in di.GetFiles())
{
file.Delete();
}
Server.MapPath gives you a directory path, not an array of files/folders. IF you want to remove all files in the folder you would do this:
var folderPath = HttpContext.Current.Server.MapPath("\\MyDirectory");
foreach (string file in Directory.GetFiles(folderPath))
{
File.Delete(file);
}
If you wanted do delete the folder, then
var folderPath = HttpContext.Current.Server.MapPath("\\MyDirectory");
Directory.Delete(folderPath);
To delete all folders within the main folder
var folderPath = HttpContext.Current.Server.MapPath("\\MyDirectory");
foreach (string file in Directory.GetDirectoriesfolderPath))
{
File.Delete(file);
}

Updating the files with new file

I have 1,000 Uniquely named folders in one large folder.
Inside of each uniquely named folder these is another folder called /images.
Inside each image folder there is a file named "Read-Web-Site-Design-{UNIQUEFOLDERNAME}-ca-logo.png"
I want to replace the 1,768 .png files (while keeping the original name) from a .png file which I am supplying.
The folder structure and filenames need to remain same. Basically I'm updating the old file with a new file, using the same (unique) name, 1,000 times.
I have written this code and I am able to get all the files and directories in loop but I want to know how will I update files here,please check my code:
private List<String> DirSearch(string sDir)
{
List<String> files = new List<String>();
try
{
foreach (string f in Directory.GetFiles(sDir))
{
files.Add(f);
}
foreach (string d in Directory.GetDirectories(sDir))
{
files.AddRange(DirSearch(d));
}
}
catch (System.Exception excpt)
{
//MessageBox.Show(excpt.Message);
}
return files;
}
Simply you have to do a File.Copy() to replace old files with new .png file you are supplying.
Assuming you will have all the files to be replaced in the list,
List<String> files = new List<String>();
foreach (var file in files)
{
if (!string.IsNullOrWhiteSpace(file))
{
File.Copy("New File Path", "file to be replaced", true);
}
}
See, you are passing true as the 3rd parameter of the Copy() method, Which is to overrite if there is a file already in the destination path.
or you can use File.Replace(). Here you can keep the original file as a backup.
File.Replace("New File", "File to be replaced", "Back up of Original File");
You may wish to consider the following, It will handle the recursion for you, only find png files that have "Read-Web-Site" in their file path
foreach(var file in Directory.EnumerateFiles(dir, "*.png", SearchOption.AllDirectories)
.Where(x => x.Contains("Read-Web-Site")))
{
File.Copy(file, Path.Combine(new FileInfo(file).DirectoryName,"newName.png"), true);
}
If its another file you wish to overwrite to this file instead then its the same but
File.Copy("newFile", file, true);
Edit
Even better
foreach(var file in Directory.EnumerateFiles(dir,
"Read-Web-Site*.png",
SearchOption.AllDirectories))

C# - Search for Matching FileNames in a Directory using SearchOption

Background: I'm developing a WinForms application using C# with an OpenFileDialog & FileBrowserDialog that will 1) search for a specific string in the filenames of a specified source directory 2) copy files to consolidated directory 3) convert multiple files from excel to csv files, and then 3) convert all the generated csv files into 1 big csv file using a command line executable
Example: MSDN provides a code example that lists all of the directories and files that begin with the letter "c" in "c:\". at http://msdn.microsoft.com/en-us/library/ms143448.aspx so I based my code on that...
Problem: The code doesn't copy any files to the consolidated folder so I'm pretty sure the search doesn't work.
What should I change on here? It doesn't work :
string files = "*.xlsx";
void DirSearch(string sDir)
{
try
{
foreach (string d in Directory.GetDirectories(sDir))
{
foreach (string f in Directory.GetFiles(d, files))
{
// Is this the file we are looking for?
// check excel files for corp name in the filename.
if (f.Contains(m_sc.get_Corp()))
{
// check if thread is cancelled
if (m_EventStop.WaitOne(0, true))
{
// clean-up operations may be placed here
// ...
// inform main thread that this thread stopped
m_EventStopped.Set();
return;
}
else
{
string path = sDir;
string searchPattern = m_sc.get_Corp();
// A file has been found in this directory
DirectoryInfo di = new DirectoryInfo(path);
DirectoryInfo[] directories = di.GetDirectories(searchPattern, SearchOption.TopDirectoryOnly);
foreach (FileInfo file in files)
{
try
{
// Copy each selected xlsx files into the specified TargetFolder
System.IO.File.Copy(FileName, consolidatedFolder + #"\" + System.IO.Path.GetFileName(FileName));
Log("File" + FileName + " has been copied to " + consolidatedFolder + #"\" + System.IO.Path.GetFileName(sourceFileOpenFileDialog.FileName));
// Convert each selected XLSX File to CSV Using the command prompt code...
}
}
}
}
The code you've posted does two separate search loops:
first:
foreach (string d in Directory.GetDirectories(sDir))
{
foreach (string f in Directory.GetFiles(d, files))
{
// Is this the file we are looking for?
// check excel files for corp name in the filename.
if (f.Contains(m_sc.get_Corp()))
{
then within that it also does:
string path = sDir;
string searchPattern = m_sc.get_Corp();
// A file has been found in this directory
DirectoryInfo di = new DirectoryInfo(path);
DirectoryInfo[] directories = di.GetDirectories(searchPattern, SearchOption.TopDirectoryOnly);
foreach (FileInfo file in files)
{
In the first one you are looking for files matching m_sc.get_Corp();, in the second one you are lookinf for directories...
In fact... your code (pseudo-code?) makes no sense...
Try:
taking your time
tidying up the code yourself
if you rewrite it slowly and break this into smaller chunks, you might spot what you are doing wrong.
Try cleaning up a bit, below is some code that will put you on the path, I've excluded the CSV conversion and the merge, hopefully you will get the idea.
private void YourFileRoutine(string sourceDirectoryPath, string consolidatedDirectoryPath)
{
var excelFiles = new DirectoryInfo(sourceDirectoryPath).GetFiles().Where(x => x.Extension == ".xlsx");
//Copy all Excel Files to consolidated Directory
foreach (var excelFile in excelFiles)
{
FileInfo copiedFile = excelFile.CopyTo(String.Concat(consolidatedDirectoryPath, excelFile.Name)); // Make sure consolidatedDirectoryPath as a "\" maybe use Path.Combine()?
// ConvertToCSV( Do your CSV conversion here, the Path will be = Path.GetFullPath(copiedFile);
}
// Merge CSV's
var csvFiles = new DirectoryInfo(consolidatedDirectoryPath).GetFiles().Where(x => x.Extension == ".csv");
// SomeMergeMethod that iterates through this FileInfo collection?
}

Categories

Resources