I have a path "C:\Users\Web References"
Under the "Web References" folder, i have *.wsdl file
I want to get the full filename of the *.wsdl file
Thanks!
Something like this:
var files = Directory.GetFiles("C:\\Users\\Web References", "*.wsdl", SearchOption.AllDirectories);
This will return a collection of files - there could be more than one wsdl file in the directory. Take the first:
var wsdlFile = files.FirstOrDefault();
Seeing that no-one is mentioning it: Path.GetFullPath()
First, you have to find it:
var files = Directory.GetFiles(path, "*.wsdl");
and now files will contain full paths to all WSDL files (if any) in path.
// find files by filter
var result = Directory.GetFiles("C:\\Users\\Web References\\", "*.wsdl");
//if you have only one file
return System.IO.Path.GetFileName(result[0]); // "my.wsdl"
The Path class will help you extract just the filename from a file path:
string path = #"C:\Users\Web References";
string[] files = Directory.GetFiles(path, "*.wsdl");
foreach (string filePath in files) {
string filename = Path.GetFileName(filePath); // e.g. myFile.wsdl
}
or using linq
var files = from f in Directory.GetFiles((#"C:\Users\Web References")
where f.EndsWith(".wsdl")
select f;
foreach (var file in files)
...
Related
How to delete Files there names containing a specific string in a Directory and also all Subdirectories?
Given Filenames like:
EA myown EURJPY M15 3015494.mq5
EA myown EURJPY M15 3015494.ex5
EA self EURJPY M15 3098111 fine.mq5
EA self EURJPY M15 3098111 fine.ex5
Given Folderstructures like:
D:\TEMP\MYTEST
D:\TEMP\MYTEST\EURJPY
D:\TEMP\MYTEST\EURJPY\EURJPY_M15
Example: I want to delete ALL Files in all Subdirectories containing this String:
3015494
These Files are copied more than one time down of the Root-Folder "D:\TEMP\MYTEST" and also copied into the Subdirectories.
I try to write a little function for this. But i can delete Files into a given Folder, but not down into Subfolders ...
Last Code from me:
// call my function to delete files ...
string mypath = #"D:\TEMP\MYTEST\";
string myfilecontains = #"xx";
DeleteFile(mypath, true, myfilecontains);
// some code i found here and should delete just Files,
// but only works in Root-Dir.
// Also will not respect my need for Filename contains Text
public static bool DeleteFile(string folderPath, bool recursive, string FilenameContains)
{
//Safety check for directory existence.
if (!Directory.Exists(folderPath))
return false;
foreach (string file in Directory.GetFiles(folderPath))
{
File.Delete(file);
}
//Iterate to sub directory only if required.
if (recursive)
{
foreach (string dir in Directory.GetDirectories(folderPath))
{
//DeleteFile(dir, recursive);
MessageBox.Show(dir);
}
}
//Delete the parent directory before leaving
//Directory.Delete(folderPath);
return true;
}
What i have to change in this Code for my needs?
Or is there a complete different code something more helpfull?
I hope you have some good ideas for me to catch the trick.
DirectoryInfo dir = new DirectoryInfo(mypath);
// get all the files in the directory.
// SearchOptions.AllDirectories gets all the files in subdirectories as well
FileInfo[] files = dir.GetFiles("*.*", SearchOption.AllDirectories);
foreach (FileInfo file in files)
{
if (file.Name.Contains(myfilecontains))
{
File.Delete(file.FullName);
}
}
This is similar to hossein's answer but in his answer if the directory name contains the value of myfilecontains that file will get deleted as well which I would think you don't want.
//get the list of files in the root directory and all its subdirectories:
string mypath = #"D:\TEMP\MYTEST\";
string myfilecontains = #"xx";
var files = Directory.GetFiles(mypath, "*", SearchOption.AllDirectories).ToList<string>();
//get the list of file for remove
var forDelete = files.Where(x => x.Contains(myfilecontains));
//remove files
forDelete.ForEach(x => { File.Delete(x); });
hope this helps!
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'm receiving an error Access to the path ... is denied when I attempt to read the files from a specified path. The code that demonstrates the error is below:
string path = "D:\\Study\\Прога 4 семестр\\Курсач\\tests";
StreamReader sr = new StreamReader(path);
while(!sr.EndOfStream)
{
string s = Path.GetFileNameWithoutExtension(path);
listBox1.Items.Add(s);
}
sr.Close();
What exactly is wrong with the code that an error occurs? How do I accomplish my goal?
Use Directory.EnumerateFiles to get all files in directory, and then project each file path to file name:
var names = Directory.EnumerateFiles(path)
.Select(f => Path.GetFileNameWithoutExtension(f));
Or even shorter way:
Directory.EnumerateFiles(path).Select(Path.GetFileNameWithoutExtension);
Unfortunately your using incorrect syntax. StreamReader will read a file, it will not retrieve a file. What you should do is use the Directory functionality from System.IO.
Example:
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string[] files = Directory.GetFiles(path);
foreach(string item in files)
Console.WriteLine(item);
That would actually retrieve file data.
A secondary example:
var path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var file = Directory.EnumerateFiles(path, "*.*", SearchOption.AllDirectories)
.Select(Path.GetFileName);
The Microsoft Developer Network has some terrific articles on different approaches to handle retrieval of files or directories from the system.
You can use Directory which has a method GetFiles(String) (+ 2 overloads) to enumerate and process files on older versions of .NET Frameworks.
string path = "D:\\Study\\Прога 4 семестр\\Курсач\\tests";
string[] fileNames = Directory.GetFiles(path);
for(int i = 0; i < fileNames.Length; i++)
{
string fileName = Path.GetFileNameWithoutExtension(path + "\\" + fileNames[i]);
listBox1.Items.Add(fileName);
}
I have a folder - "C:\scripts"
Within "scripts" I have several sub folders e.g. - "C:\scripts\subfolder1" "C:\scripts\subfolder2" etc, that contain html files.
I am trying to use the following code -
foreach (string file in Directory.EnumerateFiles(#"C:\scripts","*.html"))
{
string contents = File.ReadAllText(file);
}
However this does not work due to the html files being in the sub folders.
How can I access the html files in the sub folders without having to manually put in the path of each sub folder?
use this overload from DirectoryInfo
var dir = new DirectoryInfo(#"c:\scripts");
foreach(var file in dir.EnumerateFiles("*.html",SearchOption.AllDirectories))
{
}
Directory.EnumerateFiles(#"C:\scripts","*.html",SearchOption.AllDirectories)
Seems to be the right solution for me try it :)
Maybe this works?
foreach (string file in Directory.GetFiles("C:\\Scripts\\", "*.html", SearchOption.AllDirectories))
{
string contents = File.ReadAllText(file);
}
From SearchOption.AllDirectories
Includes the current directory and all its subdirectories in a search
operation. This option includes reparse points such as mounted drives
and symbolic links in the search.
Try like this;
var d = new DirectoryInfo(#"c:\scripts");
foreach(var fin d.EnumerateFiles("*.html", SearchOption.AllDirectories))
{
}
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.