Get names of all files in path - c#

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);
}

Related

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
}

zip files with same names but different extensions using Ioniz.Zip DLL

I need help in writing a function which zips all files with same name but different extensions in a folder.I am using Ionic.Zip dll to achieve this.I am using .Net compact framework 2.0,VS2005. My code looks like this:
public void zipFiles()
{
string path = "somepath";
string[] fileNames = Directory.GetFiles(path);
Array.Sort(fileNames);//sort the filename in ascending order
string lastFileName = string.Empty;
string zipFileName = null;
using (ZipFile zip = new ZipFile())
{
zip.AlternateEncodingUsage = ZipOption.AsNecessary;
zip.AddDirectoryByName("Files");
for (int i = 0; i < fileNames.Length; i++)
{
string baseFileName = fileNames[i];
if (baseFileName != lastFileName)
{
zipFileName=String.Format("Zip_{0}.zip",DateTime.Now.ToString("yyyy-MMM-dd-HHmmss"));
zip.AddFile(baseFileName, "Files");
lastFileName = baseFileName;
}
}
zip.Save(zipFileName);
}
}
The problem:The folder will have 3 files with same name but their extensions will be different.Now,these files are being FTPed by a device so the filenames are auto-generated by it and I have no control over it.So,for example,there are 6 files in the folder:"ABC123.DON","ABC123.TGZ","ABC123.TSY","XYZ456.DON","XYZ456.TGZ","XYZ456.TSY". I have to zip the 3 files whose names are "ABC123" together and other 3 files with names "XYZ456".As I said,I wouldnt know the names of the files and my function has to run in background.My current code zips all the files in a single zip folder.
Can anyone please help me with this?
Try out the following code
string path = #"d:\test";
//First find all the unique file name i.e. ABC123 & XYZ456 as per your example
List<string> uniqueFiles=new List<string>();
foreach (string file in Directory.GetFiles(path))
{
if (!uniqueFiles.Contains(Path.GetFileNameWithoutExtension(file)))
uniqueFiles.Add(Path.GetFileNameWithoutExtension(file));
}
foreach (string file in uniqueFiles)
{
string[] filesToBeZipped = Directory.GetFiles(#"d:\test",string.Format("{0}.*",file));
//Zip all the files in filesToBeZipped
}

How to move a file to a subdirectory ? C#

I wanna do a C# application that does this:
Selects a folder
Copies all the files from that folder into that folder +/results/
Very simple, but can't get it work.
Here is my code:
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
foreach (string file in files)
{
MessageBox.Show(Path.GetFullPath(file));
//string path=Path.Combine(Path.GetFullPath(file), "results");
//MessageBox.Show(path);
string path2 = Path.GetDirectoryName(file);
path2 = Path.Combine(Path.GetDirectoryName(file), #"results\");
path2 = Path.Combine(path2, file);
MessageBox.Show(path2);
}
First, create the destination directory, if not exists
string[] files = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
string destPath = Path.Combine(folderBrowserDialog1.SelectedPath, "results");
if(Directory.Exists(destPath) == false)
Directory.CreateDirectory(destPath);
then inside your loop
foreach (string file in files)
{
string path2 = Path.Combine(destPath, Path.GetFileName(file));
File.Move(file, path2);
}
Please note that File.Move cannot be used to overwrite an existing file.
You will get an IOException if the file exist in the destination directory.
If you only want to copy, instead of Move, simply change the File.Move statement with File.Copy(file, path2, true);. This overload will overwrite your files in the destination directory without questions.
If you are trying to move the files (and not copy them) to the new sub-folder then...
DirectoryInfo d = new DirectoryInfo(folderBrowserDialog1.SelectedPath);
foreach (FileInfo f in d.GetFiles())
{
string fold = Path.Combine(f.DirectoryName, #"results\");
if (!Directory.Exists(fold))
Directory.CreateDirectory(fold);
File.Move(f.FullName, Path.Combine(fold, f.Name));
}
This is just an example to answer the question directly but you should also handle exceptions, etc. For instance, this example assumes the user will have permission to create the directory. Furthermore, it assumes file(s) do not already exist in the destination directory with the same name(s). How you handle such scenarios depends on your requirements.
If you want to relocate the entire directory, you can use Directory.Move to achieve this.
string path1 = Path.GetDirectoryName(file);
string path2 = Path.Combine(Path.GetDirectoryName(file), #"results\");
Directory.Move(path1, path2);
Or if you just want to copy the folder (without deleting the first directory), you'll need to do it manually.
string path1 = Path.GetDirectoryName(file);
string path2 = Path.Combine(Path.GetDirectoryName(file), #"results\");
foreach(var file in Directory.GetFiles(path1))
{
File.Copy(file, Path.Combine(path2, file));
// File.Move(file, Path.Combine(path2, file)); // use this to move instead of copy
}
I haven't tested this, so some modifications might be necessary

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?
}

get full filename

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)
...

Categories

Resources