System.IO.File.Delete invalid characters - c#

I'm trying to delete all files in a directory by doing this:
System.IO.File.Delete(directoriodestino_imagenes + #"\*.*");
Where, directoriodestino_imagenes = "C:\\dcm\\patients\\NAME_LASTNAME\\DCM\\".
And I get this:
{"Illegal characters in path."}
Any hints what I may be doing wrong?

It's the wildcard character. You cannot delete multiple files using Delete method. You either need to delete the whole folder (look at the Delete folder method at http://msdn.microsoft.com/en-us/library/fxeahc5f(v=vs.110).aspx) or just remove them one by one. E.g. like in Deleting multiple files with wildcard

Actually it is possible to delete Files in a folder. Here is how I do it.
string directory = #"C:\File Downloader\DownloadedFile\";
string[] file = Directory.GetFiles(directory); // get all files in the folder.
foreach (string fileName in file )
File.Delete(fileName );

Related

asp.net 404 - File or directory not found on website but locally it can

I have a folder "res/resx/" which contatins .resx files. What I want is to get all those .resx files.
Here is my code for that.
var Path = Server.MapPath("~/");
var SampleUrl = System.IO.Path.GetFullPath(System.IO.Path.Combine(Path, "Res/resx/"));
string[] files= System.IO.Directory.GetFiles(SampleUrl);
var AllFiles = new System.Collections.ObjectModel.ReadOnlyCollection<string>(files);
foreach (string sFileName in AllFiles)
{
Response.write(sFileName + " <br>");
}
This code is working on my local and i was able to see a list of my resx files. But when i deploy this to my website and access it, an error occurs on the 2nd line of code which says:
Could not find a part of the path
'D:\Websites\mywebsite.com\Res\resx'
I tried allowing directory browsing to see if my files exist. In my local, i can browse the files but on the website, I cannot. And it seems the system cannot find the folder "Res/Resx" too. it says:
404 - File or directory not found. The resource you are looking for
might have been removed, had its name changed, or is temporarily
unavailable.
But the folder exist and it is running on my local. Any advice as to what i should do or is their something i have missed? Thanks
Try this
string[] filePaths = Directory.GetFiles(Server.MapPath("Your folder"));
Look at the System.IO.Directory class and the static method GetFiles. It has an overload that accepts a path and a search pattern. Example:
string[] files = System.IO.Directory.GetFiles(path, "*.resx");
answered by
Anthony Pegram here.

How to copy old folder to new folder and rename files in the new folder

The old folder name is 'dat' and all the files under 'dat' folder are prefixed with the folder name, i.e 'dat'.
Example:
dat/dat_x1.dat
dat/dat_b1.dat
etc
I would like to create a new folder, say 'datNew' and add all the files of 'dat' folder into 'datNew' folder. However, this time, the prefix of the files in the 'datNew' folder takes the new folder name 'datNew'. Then, it will give the following:
datNew/datNew_xt.dat
datNew/datNew_b1.dat
etc
I use the following colde to copy but am unable to search the prefix in the files and replace them with the new prefix
File.Copy(Path.Combine(dat, fName), Path.Combine(datNew, fName))
How can I rename the prefix of the files in the new folder?
You should get a folder object, and then iterate through each of the file objects within it. For each one, get the old file name, and then determine the new file name. Still in the for each, copy from old to new. Your resulting code would be:
File.Copy(Path.Combine(dat, fName), Path.Combine(datNew, fNameNew))
To determine the new prefix, something like:
var newFilename = fName.Replace(dat, datNew);
Following will do the job:
File.Copy(Path.Combine(dat, fName), Path.Combine(datNew, fName.Replace(dat,dataNew)))
This simple modification resolved my problem
File.Copy(Path.Combine(dat, fName), Path.Combine(datNew, Replace(fName, "old-prefix", "new-prefix")))

Selective deletion of files in folder according to the name

I would like to know (using c#) how I can delete files in a certain directory whose name contains *mhz.prj.
In fact there are several files in this folder and I want to delete only Amhz.prj Bmhz.prj for example. My problem is that the end of the filename is important.
This will loop through C:\MyDir and delete any files with the extension prj.
foreach(var file in Directory.GetFiles(#"C:\MyDir", "*.prj"))
{
File.Delete(Path.GetFullPath(file));
}

C# How to grep the last word from a directory path?

I have a program that "greps" out various directory paths from a log text file and prints various results according to the word.
Examples of Directory paths:
C:/Documents and Settings/All Users/Desktop/AccessData FTK Imager.lnk
C:/Documents and Settings/All Users/Start Menu/Programs/AccessData
C:/Documents and Settings/Administrator/Desktop/AccessData FTK Imager.exe:Zone.Identifier
Therefore how can I grep out the file or folder name after the last "/"? This is to help the program to identify between files and folder. Please do take note of the multiple "." and white spaces found within a directory paths. etc "Imager.exe:Zone.Identifier". Therefore it is difficult to use if(!name.contains()".")
Etc. How to get the "AccessData FTK Imager.lnk" or "AccessData" or "AccessData FTK Imager.exe:Zone.Identifier" from the path STRING?!
May someone please advise on the methods or codes to solve this problem? Thanks!
The codes:
if (!token[7].Contains("."))
{
Console.WriteLine("The path is a folder?");
Console.WriteLine(token[7]);
Console.WriteLine(actions);
MacActions(actions);
x = 1;
}
Use the Path class when working with file paths, and use the File and Directory class when working with actual files and folders.
string str1=#"C:/Documents and Settings/All Users/Desktop/AccessData FTK Imager.lnk";
string str2=#"C:/Documents and Settings/All Users/Start Menu/Programs/AccessData";
string str3=#"C:/Documents and Settings/Administrator/Desktop/AccessData FTK Imager.exe:Zone.Identifier";
Console.WriteLine(Path.GetFileName(str1));
Console.WriteLine(Path.GetFileName(str2));
Console.WriteLine(Path.GetFileName(str3));
outputs:
AccessData FTK Imager.lnk
AccessData
Zone.Identifier <-- it chokes here because of the :
This class operates on strings, as I do not have those particular files and/or folders on my system. Also it's impossible to determine whether AccessData is meant to be a folder or a file without an extension.
I could use some common sense and declare everything with an extension to be a file (Path.GetFileExtension can be used here) and everything else to be a folder.
Or I could just check it the string in question is indeed a file or a folder on my machine using (File.Exists and Directory.Exists respectively).
if (File.Exists(str2))
Console.WriteLine("It's a file");
else if (Directory.Exists(str2))
Console.WriteLine("It's a folder");
else
Console.WriteLine("It's not a real file or folder");
Use Path.GetFileName.
The characters after the last directory character in path. If the last character of path is a directory or volume separator character, this method returns String.Empty.
This is to help the program to identify between files and folder
There is no way to determine is a path represents a file or folder, unless you access the actual file system. A directory name like 'Foo.exe' would be perfectly valid, and a file with no extension ('Foobar') would be valid too.
how about tokenized it with "/" like what you're doing ... and then you'll know that the last token is the file, and whatever before it is the path.
You can simply split the whole string by /
e.g.:
string a="C:/Documents and Settings/All Users/Desktop/AccessData FTK Imager.lnk";
string[] words=a.split('/');
int len=words.length;
so now words[len] returns the data after last slash(/)..
I hope you understand...
I guess you only have a string that represents the name of the file, if that is the case you can't really be sure. It's totally ok to have a folder namen something like Folder.doc. So if you don't have access to the actual file system it is hard to check. You can get close though using regular expression like:
(.*\\)(.+)(\..*)
Try it on: http://www.regexplanet.com/simple/index.html
If you get any output in group number 3 it's likely that it is a file and not a folder. If you don't get some output try this direct after:
(.*\\)(.+)(\..*)?
That will give you the folder in group 2.

Searching for a file with C#

What would be the fastest way to search for a file programtically in C#. I know the relative location of the file, lets say its "abcd\efgh\test.txt". I also know that this file is on my E:\ drive. "abcd" is a subdirectory on some directory in E:\ drive.
Thanks
Since you know the root directory you want to search and a string pattern for a filename, you can create a DirectoryInfo with the root directory:
DirectoryInfo dir = new DirectoryInfo(#"E:\");
And then call GetFiles() to get all the matches. Passing SearchOption.AllDirectories will ensure the search is recursive.
List<FileInfo> matches =
new List<FileInfo>(dir.GetFiles(partialFilename,
SearchOption.AllDirectories));
Or if you know part of the path (instead of the filename):
List<DirectoryInfo> matches =
new List<DirectoryInfo>(dir.GetDirectories(partialDirectoryName,
SearchOption.AllDirectories));
And then you can navigate to the file from there.
So if I understand correctly you know the path will be of the form:
"E:\\" + something + "\\abcd\\efgh\\test.txt"
If something is only 1 level deep, then simply get all directories on your E:, and then try to do a file open on each of those subdirectories.
If something is more than 1 level deep, then do a recursive call to get the directories until you find abcd.
The fastest way would probably be to use FindFirstFile etc api but I would have thought that you could do it fairly quickly (And much easier) with Directory.GetDirectories (to find the right sub direcotry) and then Directory.GetFiles to find the actual file.
Just the use File.Exists method and iterate through all possible filenames. Maybe something like this (not tested):
string SearchInFolder(string root) {
if (File.Exists(Path.Append(root, "\\abcd\\efgh\\test.txt")) return Path.Append(root, "\\abcd\\efgh\\test.txt");
foreach(var folder in Directory.GetDirectories(root)) {
var fullFile = Path.Append(folder, "\\abcd\\efgh\\test.txt");
if (File.Exists(fullFile)) {
// Found it !!!!
return fullFile;
} else {
var result = SearchInFolder(folder);
if (result != null) return result;
}
}
return null;
}
But this will seach the whole E:\ drive for the pattern, also subfolders are searched.
I think the algorithm would be start at e:\ and read all directories. If one of them is \abcd\, immediately check for the rest of the path and file, e.g., efgh\test.txt.
If e:\ does NOT have \abcd\, then you need to traverse into each subdirectory and do the same check. Does \abcd\ exist? Yes, check for efgh\text.txt. No? Traverse subdirs.
If you need the absolutely fastest, when you fail to find \abcd\, and you have your list of subdirs you must now go check, you could introduce some level of threading. But that could get hairy rather quickly.

Categories

Resources