GetFiles with spaces in filename - c#

I use the following code to take all the files from a directory and search for a specific file:
string [] fileEntries = Directory.GetFiles("C:\\uploads");
foreach(string fileName in fileEntries)
if (fileName.Contains(name))
PicturePath = fileName;
where "name" is a string which I get from DB.
It seems to work to an extend but if my file contains a space in fileName it only takes the first string from fileName which is the first string before the white space, ignoring th rest. How can i take the full fileName (as well as the path to that file accordingly).
For example: I have a file named "ALEXANDRU ALINA.jpg" inside uploads and in name i have the string "ALEXANDRU ALINA". When I run that code (writing the PicturePath) it displays just "ALEXANDRU".

This might be what you're looking for:
string[] fileEntries = Directory.GetFiles("C:\\uploads");
foreach (string fileName in fileEntries)
{
FileInfo fi = new FileInfo(fileName);
if (fi.Name.Equals(name, StringComparison.CurrentCultureIgnoreCase)) PicturePath = fileName;
}
What you're attempting to do is find the target file name within the whole path, but the method you're using could produce errors (what if the name is contained within part of the folder path?). By using the System.FileInfo class and its Name property, which is the file name only (not the full file path which includes the containing folder path), you won't be needlessly searching any part of the folder path.

Related

Get file path and file name from directory - C#

I am trying to get the file path and file name of I file I upload in a folder. I have the paths like so:
string path = Path.Combine(_webHost.ContentRootPath, "Uploads\\ZipFiles\\");
string extractPath = Path.Combine(_webHost.ContentRootPath, "Uploads\\ExtractedFiles\\");
I upload my file in path and I unzip the file in extractPath.
string fullPath = Path.GetFullPath(extractPath);
string fileName = Path.GetFileName(extractPath);
fullPath returns the correct path but fileName is empty. I don't get the file name.
I am trying to get something like this
var dbfPath = "C://ExtractedFiles//fileName.jpg";
I was planning on getting the file path in one variable and the file name in another and then concatenate them but I can't get the file name. What's the best way to do this?
To get the files in the ExtractedFiles folder :
string[] files = Directory.GetFiles(extractPath)
If your zip have folders inside, and you want to get all the file inside them recursively use :
string[] files = Directory.GetFiles(extractPath, "*.*", SearchOption.AllDirectories)

Adjusted output for looping through a directory

I have a bit of code that is directed to loop through a directory and display the results in a listbox. I have everything working, but the output displays the entire file path (\server\directory\directory\subdirectory\filename.filetype) in the listbox. Ideally, I would like this to display just the filename and the filetype (ie. workbook1.xlsm).
string[] filePaths = Directory.GetFiles(#"\\Server\directory\Folder\Folder\", "*.xlsm",
SearchOption.AllDirectories);
statusCodeLB.Items.Clear();
foreach (string file in filePaths)
{
statusCodeLB.Items.Add(file);
}
statusLabel.Text = statusCodeLB.Items.Count.ToString();
Also, Is there any way to get this to be fully functional on a Mac OS X (10.6 and 10.7 to be precise)?
I have everything working, but the output displays the entire file path (\server\directory\directory\subdirectory\filename.filetype) in the listbox. Ideally, I would like this to display just the filename and the filetype (ie. workbook1.xlsm).
You are looking for Path.GetFileName(path), documented here. The documentation reads as follows:
Returns the file name and extension of the specified path string.
string[] filePaths = Directory.GetFiles(#"\\Server\directory\Folder\Folder\", "*.xlsm",
SearchOption.AllDirectories);
statusCodeLB.Items.Clear();
foreach (string file in filePaths)
{
statusCodeLB.Items.Add(Path.GetFileName(file));
}
statusLabel.Text = statusCodeLB.Items.Count.ToString();
If the file was (input) "C:\Some\Directory\Structure\fileName.ext" the resulting string added to the ListBox.Items would be (output) fileName.ext.

How to get files with desired name in C# using Directory.Getfile?

I am trying to obtain a file of name "fileName.wav" from the directory whose path has been specified im not able to get the desired function .. any help in this regard is appreciated.
static void Main(string[] args)
{
string[] fileEntries = Directory.GetFiles(
#"D:\project\Benten_lat\BentenPj_000_20141124_final\Testing\DPCPlus\Ref\Generated_Ref_Outputs_MSVS", "*.wav");
foreach (string fileName in fileEntries)
{
string[] fileEntries1 = Directory.GetFiles(
#"D:\project\older versions\dpc_latest\Testing\DPCPlus\input");
foreach (string fileName1 in fileEntries1)
{
Console.WriteLine(Path.GetFileName(fileName1));
}
}
}
This Code will search for all .xml extension files with matches abCd name from C:\\SomeDir\\ folder.
string cCId ="abCd";
DirectoryInfo di = new DirectoryInfo("C:\\SomeDir\\");
FileInfo[] orderFiles = di.GetFiles("*" + cCId + "*.xml", SearchOption.TopDirectoryOnly);
You should change this code according to your needs.
Hope this helps you.
If you want to extract name and extension from a file-path, you can use following code:
string result = Path.GetFileName(yourFilePath); // result will be filename.wav
You can not use GetFiles method for a file path!
Directory.GetFiles(#"D:\project\Benten_lat\BentenPj_000_20141124_final\Testing\DPCPlus\Ref\Generated_Ref_Outputs_MSVS\filename.wav") //Error
The input for this method should be a directory!
Assumptions based on your question (please correct me if I am wrong):
You know the folder (e.g. the user entered it)
You know the file name (e.g. it is hard coded because it must be the same always)
In this case you do not really need to search the file.
Solution:
string folderPath = #"D:\somewhere";
string fileName = "file.wav";
string filePath = Path.Combine(folderPath, fileName);
if (File.Exists(filePath))
{
// continue reading the file, etc.
}
else
{
// handle file not found
}

The directory name is invalid

Why am I getting this error? I am using the correct path.
Problem : You are providing the Path of File
Solution : You need to provide the path of Directory to get all the files in a given Directory based on your search pattern.
From MSDN: Directory.GetFiles()
Returns the names of files (including their paths) that match the
specified search pattern in the specified directory.
Try this:
string directoryName = Path.GetDirectoryName(e.FullPath);
foreach(String filename in Directory.GetFiles(directoryName,"*.eps"))
{
//your code here
}
You want the directory, not the filename.
At the moment, the value of e.FullPath is "C:\\DigitalAssets\\LP_10698.eps". It should be "C:\\DigitalAssets".
string[] fileNames = Directory.GetFiles(string path) requires a directory, you are giving it a directory + filename.
MSDN:
Returns the names of files (including their paths) that match the
specified search pattern in the specified directory.
foreach(string filename in Directory.GetFiles(e.FullPath, "*.eps"))
{
// For this to work, e.FullPath needs to be a directory, not a file.
}
You can use Path.GetDirectoryName():
foreach(string filename in Directory.GetFiles(Path.GetDirectoryName(e.FullPath), "*.eps"))
{
// Path.GetDirectoryName gets the path as you need
}
You could create a method:
public string GetFilesInSameFolderAs(string filename)
{
return Directory.GetFiles(Path.GetDirectoryName(filename), Path.GetExtension(filename));
}
foreach(string filename in GetFilesInSameFolderAs(e.FullPath))
{
// do something with files.
}
e.FullPath seems to be a file, not a directory. If you want to enumerate *.eps files, the first argument to GetFiles should be a directory path: #"C:\DigitalAssets"
the first argument of GetFiles should be only "C:\DigitalAssets"
e.FullPath include the file name in it.
Directory.GetFiles used to get file names from particular directory. You are trying to get files from file name which is not valid as it gives you error. Provide directory name to a function instead of file name.
You can try
Directory.GetFiles(System.IO.Path.GetDirectoryName(e.FullPath),"*.eps")
For deleting files from a directory
var files = Directory.GetFiles(directory)
foreach(var file in files)
{
File.Delete(file);
}
In short to delete the file use
File.Delete(filePath);
and to delete the directory
Directory.Delete(directoryPath)

How can I just get the base filename from this C# code?

I have the following code:
string[] files = Directory.GetFiles(#"C:\Notes", "*.txt", SearchOption.TopDirectoryOnly);
foreach(string file in files)
When I check the contents of file it has the directory path and extension. Is there a way I can just get the filename out of that?
You can use the FileInfo class:
FileInfo fi = new FileInfo(file);
string name = fi.Name;
If you want just the file name - quick and simple - use Path:
string name = Path.GetFileName(file);
You can use the following method: Path.GetFileName(file)
System.IO.FileInfo f = new System.IO.FileInfo(#"C:\pagefile.sys"); // Sample file.
System.Windows.Forms.MessageBox.Show(f.FullName); // With extension.
System.Windows.Forms.MessageBox.Show(System.IO.Path.GetFileNameWithoutExtension(f.FullName)); // What you wants.
If you need to strip away the extension, path, etc. you should fill this string into a FileInfo and use its properties or use the static methods of the Path class.

Categories

Resources