Directory.EnumerateFiles not retrieving the actual path - c#

Am trying to loop through a folder and read all the XML files within it.
Am using the Directory.EnumerateFiles to read from the path.
My .cs file and the XML files folder lies in same path
"C:\User\Documents\Projects\TestTool"
Am using the below code to get read the files.
string path = #"..\TestCases\";
foreach(string file in Directory.EnumerateFiles(path, "*.xml"))
{
}
Using this am getting exception stating
Could not find path "C:\Program Files(x86)\Common Files\Microsoft
Shared\DevServer\TestCases"
This is pointing to the WebDev.WebServer20 path instead of the actual path.
Not sure why it is pointing to a completely different folder
I tried string path = #"\TestCases\"; But when I try like this it is throwing an exceptiopn stating
Could not find path "C:\TestCases"
What is the mistake am making? Please help

Try it:
string path = "..\\TestCases\\";
foreach (FileInfo file in new DirectoryInfo(path).EnumerateFiles("*.xml"))
{
string filePath = file.FullName;
}

Since it is running under WebDev server it will using WebDev.WebServer20.exe's path for all relative paths.
You must use: Server.MapPath("~") to get to your own root.
string path = Server.MapPath("~") + #"\TestCases\";
foreach(string file in Directory.EnumerateFiles(path, "*.xml"))
{
}
Please note if Server.MapPath("~") points to bin, then use it like Directory.GetParent(Server.MapPath("~")) + #"\TestCases\";
Assuming this is your target directory C:\User\Documents\Projects\TestTool\TestCases

Related

Ionic.zip extraction failing - DirectoryNotFoundException

I'm trying to extract a zip file using DotNetZip. Whenever I try to extract an existing zip file with a path, I get a DirectoryNotFoundException. The path I am passing in gets changed for some reason, causing the DirectoryNotFoundException. I'm following the examples found here.
Here is my code:
string zipToUnpack = #"C:\Users\user\Desktop\data.zip";
string TmpDirectory = #"C:\Program Files\Temp";
using (ZipFile zip = ZipFile.Read(zipToUnpack))
{
zip.ExtractAll(TmpDirectory, true);
}
The DirectoryNotFoundException shows me the path it is looking in and it isn't TmpDirectory. Instead, it's TmpDirectory + another location in my ProgramFiles directory.

How to locate relative file path when using GetFiles() in C#?

I've found a few related questions but they're not working that well. The image name is a modified GUID like 3c6b4a9b-8e88-4c8e-93da-258acd2c964f_0 but the extension isn't known (.jpg, .gif, ..etc). The GUID will be coming from a gridview so it's not a static string. Below is what I have but I'm having a difficult time getting the path to work correctly.
string fileName = `3c6b4a9b-8e88-4c8e-93da-258acd2c964f`;
DirectoryInfo filePath = new DirectoryInfo(#"/Images");
MessageBox.Show(filePath.ToString());
FileInfo[] fileArray = filePath.GetFiles(fileName + "_0.*");
Keep getting issues with the directory being invalid. Currently the files are stored on my c: drive.
How can I get the relative path without hardcoding it in? I was using DirectoryInfo(Server.MapPath("Images")); which worked temporarily then started giving this error System.ArgumentException: Second path fragment must not be a drive or UNC name. which seems to be from the path having the drive "C:" This doesn't seem to be a permanent solution once the site is launched though.
The actual path is C:\Website\Name\Images\3c6b4a9b-8e88-4c8e-93da-258acd2c964f_0.jpg
Thanks!
You've used filePath as the first parameter to GetFiles, just use the wildcard and invoke the overload of GetFiles with one parameter.
filePath.GetFiles("_0.*");
The problem is that you are getting DirectoryInfo for "C:\Images".
You want to use Server.MapPath to get the physical path to the folder that is in your website (which could be anywhere on any drive).
Using the ~ means to start from the root of the running website.
So this should do the trick:
string fileName = `3c6b4a9b-8e88-4c8e-93da-258acd2c964f`;
DirectoryInfo filePath = new DirectoryInfo(Server.MapPath("~/Images"));
FileInfo[] fileArray = filePath.GetFiles(fileName + "_0.*");

Cannot create a file when it already exists using File.Move

I was trying to move a file from my Resx to my PC, but I'm keep having problems.
So I import a folder named "bad" in the Resources and I use the File.Move method to move the folder "bad" into my PC.
But the program keeps crashing because it says: Cannot create a file when its already exists.
Here the code I use:
//txtpath is the root folder. I let the user choose the root folder and save it in txtpath.text
private void btnbadname_Click(object sender, EventArgs e)
{
string source = "Resources\bad";
string destination = txtpath.Text + #"\RADS\projects\lol_air_client\releases\0.0.1.74\deploy\assets\locale\App";
File.Move(source, destination);
MessageBox.Show("脏话ID已开启, 教程请点击下面的链接");
}
The destination Directory cannot exist. In your code you are creating the Directory if it doesn't exist and then trying to move your directory, the Move Method will create the directory for you. If the Directory already exists you will need to Delete it or Move it.
See:
Cannot create a file when that file already exists when using Directory.Move
Destination supposed to have the filename as well
string destination = txtpath.Text + #"\RADS\projects\lol_air_client\releases\0.0.1.74\deploy\assets\locale\App\yourfilename.ext";
You are using File.Move to move directory, why not using Directory.Move.
The MSDN documentation will only move files from a source to a destination, while Directory.Move will move the directory itself.
If I misunderstood you, and you want to move a file;
You can check if the file exists before or not using something like:
if(File.Exists(fileName))
File.Delete(fileName);
Edit:
If you want to iterate through the directory and make sure that the file doesn't exist before moving it, you can use something like:
//Set the location of your directories
string sourceDirectory = #"";
string destDirectory = #"";
//Check if the directory exists, and if not create it
if (!Directory.Exists(destDirectory))
Directory.CreateDirectory(destDirectory);
DirectoryInfo sourceDirInfo = new DirectoryInfo(sourceDirectory);
//Iterate through directory and check the existance of each file
foreach (FileInfo sourceFileInfo in sourceDirInfo.GetFiles())
{
string fileName = sourceFileInfo.Name;
string destFile = Path.Combine(destDirectory, fileName);
if (File.Exists(destFile))
File.Delete(destFile);
//Finally move the file
File.Move(sourceFileInfo.FullName, destFile);
}
When using MoveTo, provide the full path of where you are sending the file, including the file name, eg, pic123.jpg. If you use DirectoryInfo to get an array of files and want to move any of them, append the Name property of the file to the directory path where you are sending the file.
imgFile.MoveTo("C:\myPictures\ArchiveFolder\pic123.jpg")

Ways to get the relative path of a folder

I have one folder named "Images" in my project. I want to get the path of the Image folder so that I can browse that and get the files.
I'm using below piece of code for my above requirement and it is working fine.
string basePath = AppDomain.CurrentDomain.BaseDirectory;
basePath = basePath.Replace("bin", "#");
string[] str = basePath.Split('#');
basePath = str[0];
string path = string.Format(#"{0}{1}", basePath, "Images");
string[] fileEntries = Directory.GetFiles(path);
foreach (string fileName in fileEntries)
listBox.Items.Add(fileName);
Just want to know like is there any elegant way of doing this? What are the best ways of getting the folder path?
This is what i usually use:
string appDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
Note that this returns the directory of the assembly that contains the currently executing code (i assume this is your main executable).
To get the parent directory of the resulting path, you can also use
Path.GetDirectoryName(appDirectory);
I would advice against depending on the Visual Studio project structure in your code, though. Consider adding the images folder as content to your application, so that it resides in a subdirectory in the same directory as your executable.
If you are just trying to reference a directory with a fixed relationship to another, then you can just use the same .. syntax you'd use at the command line?
You should also use the methods in the Path class (eg Path.Combine) rather than all that string manipulation.

Is there a way to find a file by just its name in C#?

We use absolut path or relatvie path to find a file in our C# application right now. Is there a way to find the file just by its name if the file is under the currect working directory or under one of the "paths"?
Use absolute pathe is not good and use relative path is not good enough because we may change project structure by rename or move project folders. If we our code can automatically search current working directory, its subfolders and search system path, that will be more flexible.
thanks,
You can easily build a recursive function to do this for you. Look at Directory.GetDirectories and Directory.GetFiles, both under System.IO
Try this:
string target = "yourFilenameToMatch";
string current = Directory.GetCurrentDirectory();
// 1. check subtree from current directory
matches=Directory.GetFiles(current, target, SearchOption.AllDirectories);
if (matches.Length>0)
return matches[0];
// 2. check system path
string systemPath = Environment.GetEnvironmentVariable("PATH");
char[] split = new char[] {";"};
foreach (string nextDir in systemPath.Split(split))
{
if (File.Exists(nextDir + '\\' + target)
{
return nextDir;
}
}
return String.Empty;
You could call Directory.GetFiles for each root folder in which you want to search for the file. the parameter searchOption allow you to specify whether the search operation look in all subdirectories or only the directory specified. E.g:
public string GetFileName(string[] folders,string fileName) {
string[] filePaths;
foreach(var folder in folders) {
filePaths=Directory.GetFiles(folder,fileName,SearchOption.AllDirectories)
if (filePaths.Lenght>0)
return filePaths[0];
}
}
Try this:
Directory.EnumerateFiles(pathInWhichToSearch, fileNameToFind, SearchOption.AllDirectories);
And, you need to use:
using System.IO;
on top of your class.
This searches all subdirectories of pathInWhichToSearch for a file with name fileNameToFind (it can be a pattern too - like *.txt) and returns result as IEnumerable<string> with full paths of found files.
You can get the exe's directory using
Path.GetDirectoryName(Application.ExecutablePath);
Example Code: http://www.csharp-examples.net/get-application-directory/
And then, you can search the folders from there using recursion. This is a good article on recursive searching for files:
http://support.microsoft.com/kb/303974

Categories

Resources