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.
Related
I have a C# console application that sends Excel spreadsheet attachments through email.
I have given the file path in App.config. While trying to find the file, the code looks at proper location. But when trying to attach the file inside the foreach statement, it is looking in code's bin folder.
What am I doing wrong here?
DirectoryInfo dir1 = new DirectoryInfo(ConfigurationManager.AppSettings.Get("FilePath"));
FileInfo[] folderFiles = null;
folderFiles = dir1.GetFiles();
foreach (FileInfo aFile in folderFiles)
{
message.Attachments.Add(new Attachment(aFile.Name));
}
You need to use aFile.FullName (includes the full path) rather than aFile.Name (only the filename). If a command is not doing what you expect, you should check the documentation.
Alternatively, you could make it simpler:
string dir1 = ConfigurationManager.AppSettings.Get("FilePath");
foreach(string aFile in Directory.EnumerateFiles(dir1))
{
message.Attachments.Add(new Attachment(aFile));
}
as Directory.EnumerateFiles simply returns the full filenames and you would have to think about not doing so (e.g. by using Path.GetFileName) to do otherwise.
I have an aspx page that I am displaying image from codehind c#.
Every item has it's own directory with images inside if there were any uploaded.
It works fine except if the directory doesn't exist for a certain item, I get a return error "Could not find part of the path....
In some cases the directory will not exist because there are no images assigned to the item. What should I include in my code to ignore this if there is no directory for the item?
Below is the code used to display the images:
string[] filePaths = Directory.GetFiles(Server.MapPath("/Test/Files/Item" + ItemNumber + "/"));
List<ListItem> files = new List<ListItem>();
foreach (string filePath in filePaths)
{
string fileName = Path.GetFileName(filePath);
files.Add(new ListItem(fileName, "/Test/Files/Item" + ItemNumber + "/" + fileName));
}
Use File.Exists method to filter out image files that are missing:
foreach (string filePath in filePaths.Where(File.Exists)) {
... //
}
You need to add using System.Linq and using System.IO in order for the above to compile.
Note: The above uses method groups for creating lambda expressions. Where(File.Exists) is a shorthand syntax for Where(f => File.Exists(f))
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.
So basically i am making an app that will sync file types is different ways, I want to search the whole of a logical Drive for example C:\ for all text files.How ever once i find all the text files i want to apply an action for example move all text files to one location or email all text files to the users email.
I have found this code from a past Stack overflow post
public List<string> Search()
{
var files = new List<string>();
foreach (DriveInfo d in DriveInfo.GetDrives().Where(x => x.IsReady))
{
try
{
files.AddRange(Directory.GetFiles(d.RootDirectory.FullName, "*.txt", SearchOption.AllDirectories));
}
catch(Exception e)
{
Logger.Log(e.Message); // Log it and move on
}
}
return files;
}
But what i want to know is how do i do somthing when i find the files ?
The code you posted looks like it should fill List<string> files with strings representing names of files that have a .txt extension.
It should be as simple as iterating over the value returned from the function and doing as you please with them.
This code should (untested) check for a target directory, create it if it doesn't exist, and then copy each file returned from Search() to the target path.
List<string> results = Search();
String targetPath = "C:/TargetDirectory/";
if (!System.IO.Directory.Exists(targetPath))
System.IO.Directory.CreateDirectory(targetPath);
foreach (string aFileStr in results)
{
String sourceFile = aFileStr;
String destFile = Path.Combine(targetPath, Path.GetFileName(aFileStr));
System.IO.File.Copy(sourceFile, destFile, true);
}
You would do a foreach on the list of strings that that function returns.
I'm not quite sure if I understand you correctly. If you just want to know how to process your filelist, you could for instance do the following:
var filelist = Search();
foreach (var s in filelist) {
string fn = System.IO.Path.GetFileName(s);
string dest = System.IO.Path.Combine("c:\\tmp", fn);
System.IO.File.Copy(s, dest, true);
}
which will copy all files in filelist to c:\tmp and overwrite files with equal filename.
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)