Trouble deleting a folder full of files - c#

This should be very simple but I'm not sure what's wrong. I'm trying to delete all the files in a folder using File.Delete.
This is what I have so far:
DirectoryInfo ImageFolder = new DirectoryInfo(Program.FolderPath + #"\Images");
foreach (var File in ImageFolder.GetFiles())
{
File.Delete(File.FullName);
}
Then the ".Delete" becomes underlined and says no overload for method delete takes 1 argument.
Any help is appreciated.

What you're seeing is called Namespace Ambiguity.
In your own code or a reference DLL you probably have a method called Delete in a Class called File that doesn't support a single string parameter.
To fix the problem fully qualify File.Delete with System.IO, eg:
System.IO.File.Delete

To delete folder full of file use:
Directory.Delete(string directoryName, bool recursive);
https://msdn.microsoft.com/en-us/library/fxeahc5f(v=vs.110).aspx
Or from your code above, use:
DirectoryInfo ImageFolder = new DirectoryInfo(Program.FolderPath + #"\Images");
foreach (var fileInfo in ImageFolder.GetFiles())
{
fileInfo.Delete(); //this is FileInfo.Delete
// or
// File.Delete(fileInfo.FullName);
// dont use reserve "File" as your variable name
}
Remember, you are calling FileInfo, not File

You have to change the naming of the variable:
DirectoryInfo ImageFolder = new DirectoryInfo(Program.FolderPath + #"\Images");
foreach (var file in ImageFolder.GetFiles())
{
File.Delete(file.FullName);
}

Related

C# mass File renamer

i want to create C# mass file renamer, here is my UI
i have created tes folder, inside of tes there's a file which is 1.txt.
i want to create my program to add prefix and suffix to the files, so 1.txt will become
prefix1suffix
but then i got an error
it's said file already exist though there's only one file on tes folder, which is 1.txt how do i make it work ? where's the error comes from ?
i have tried the following code
private void Rename(string prefix, string filepath, string suffix)
{
//i don't use prefix suffix yet to make sure if my function works
DirectoryInfo d = new DirectoryInfo(filepath);
FileInfo[] file = d.GetFiles();
try
{
foreach (FileInfo f in file )
{
File.Move(f.FullName,"stackoverflow");
}
}
catch (Exception e)
{
cmd.cetakGagal(e.ToString(), title);
}
cmd.cetakSukses("Rename Success", title);
}
and it returns same error as the second picture above.
the following picture is tes folder, there's nothing in tes folder except 1.txt
You are calling File.Move() with a full path for your sourceFileName and a relative path for your destFileName. The relative file path is relative to the current working directory and not to the source file path. I expect that a stackoverflow file exists in the current working directory, most likely created the first time you ran this code.
your File.Move is changing them all to StackOverflow not using the prefix and suffix. If you only have one file in the directory it shouldn't be an issue. Are you sure there is only 1 file?
public static void Move(
string sourceFileName,
string destFileName
)
Looking at this answer might be the clue as you are specifying relative path for the destination file. To obtain the current working directory, see GetCurrentDirectory
The sourceFileName and destFileName arguments are permitted to specify
relative or absolute path information. Relative path information is
interpreted as relative to the current working directory.
You should change
File.Move(f.FullName,"stackoverflow");
to
string fileName = f.Name.Replace(f.Extenstion,string.Empty);
string newFileName = string.Format("{0}{1}{2}",prefix,fileName,suffix);
string newFileWithPath = Path.Combine(f.Directory,newFileName);
if (!File.Exists(newFileWithPath))
{
File.Move(f.FullName,newFileWithPath);
}
The code above will give you that error since, after the first run through, "stackoverflow" exists as a file. Make sure that you check if the destination file exists (using File.Exists) before calling File.Move.
Since your goal is renaming, I would suggest using a test folder filled with files rather than using a piecemeal approach. See if something like this helps:
private void Rename(string prefix, string filepath, string suffix)
{
//i don't use prefix suffix yet to make sure if my function works
DirectoryInfo d = new DirectoryInfo(filepath);
FileInfo[] file = d.GetFiles();
try
{
foreach (FileInfo f in file )
{
f.MoveTo(#filepath + #"\" + prefix + f.Name.Insert(f.Name.LastIndexOf('.'),suffix));
}
}
catch (Exception e)
{
cmd.cetakGagal(e.ToString(), title);
}
cmd.cetakSukses("Rename Success", title);
}
on a side note using a listview to display the filenames and the changes before they're committed will help prevent unwanted changes.

Get file name of file from full path?

I have DragDrop enabled in my WinForms application, I'm getting the list of items dropped and storing them in a string array called files, then in the DragDrop event I can do something like:
foreach (string file in files)
{
MessageBox.Show(file);
}
Which would return something like:
C:\Users\MyName\document.txt
Is it possible to get just the file name + extension (e.g. document.txt)? I'm not asking for a complete solution, but could you hint me in that direction?
Use Path static function calls such as:
Path.GetFileName(someFullPath);
See msdn here.
You could also use FileInfo class ..
FileInfo fileInfo = new FileInfo(fileFullPath);
var name = fileInfo.Name;
var extension = fileInfo.Extension;

Easiest way to check if file exists within a subfolder

I am going getting all the folders within a folder as follows:
foreach (DirectoryInfo directory in root.GetDirectories())
I now want to check all the files in each of those folder individualally for an XML file.If the XML file exists I want to do something.
What would be the best way to go about this?
I know this is the basis:
if (File.Exists("*.xml"))
{
}
but that is not working?
Try this method if you want to actually do something with the XML file. If you are just checking to see if any xml file exists then I would go a different route:
foreach (DirectoryInfo directory in root.GetDirectories())
{
foreach(string file in Directory.GetFiles(directory.FullName, "*.xml"))
{
//if you get in here then do something with the file
//an "if" statement is not necessary.
}
}
http://msdn.microsoft.com/en-us/library/wz42302f.aspx
The Directory.GetFiles method:
if (Directory.GetFiles(#"C:\","*.xml").Length > 0) {
// Do something
}
As an alternative you could use Directory.GetFiles with your search pattern and action upon the found files...
var existing = Directory.GetFiles(root, "*.xml", SearchOption.AllDirectories);
//...
foreach(string found in existing) {
//TODO: Action upon the file etc..
}
foreach (DirectoryInfo directory in root.GetDirectories())
{
// What you have here would call a static method on the File class that has no knowledge
// at all of your directory object, if you want to use this then give it a fully qualified path
// and ignore the directory calls altogether
//if (File.Exists("*.xml"))
FileInfo[] xmlFiles = directory.GetFiles("*.xml");
foreach (var file in xmlFiles)
{
// do whatever
}
}

delete folder/files and subfolder

I want to delete a folder containing files and a subfolder, also containing files. I have used everything, but it is not working for me. I'm using the following function in my web-application asp.net:
var dir = new DirectoryInfo(folder_path);
dir.Delete(true);
Sometimes it deletes a folder, or sometimes it doesn't. If a subfolder contains a file, it only deletes the file, and not the folder as well.
Directory.Delete(folder_path, recursive: true);
would also get you the desired result and a lot easier to catch errors.
This looks about right: http://www.ceveni.com/2008/03/delete-files-in-folder-and-subfolders.html
//to call the below method
EmptyFolder(new DirectoryInfo(#"C:\your Path"))
using System.IO; // dont forget to use this header
//Method to delete all files in the folder and subfolders
private void EmptyFolder(DirectoryInfo directoryInfo)
{
foreach (FileInfo file in directoryInfo.GetFiles())
{
file.Delete();
}
foreach (DirectoryInfo subfolder in directoryInfo.GetDirectories())
{
EmptyFolder(subfolder);
}
}
The easiest way in my experience is this
Directory.Delete(folderPath, true);
But I am experiencing a problem with this function in a scenario when I am trying to create the same folder right after its deletion.
Directory.Delete(outDrawableFolder, true);
//Safety check, if folder did not exist create one
if (!Directory.Exists(outDrawableFolder))
{
Directory.CreateDirectory(outDrawableFolder);
}
Now when my code tries to create some file in the outDrwableFolder it ends up in exception. like for instance creating image file using api Image.Save(filename, format).
Somehow this piece of helper function works for me.
public static bool EraseDirectory(string folderPath, bool recursive)
{
//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))
{
EraseDirectory(dir, recursive);
}
}
//Delete the parent directory before leaving
Directory.Delete(folderPath);
return true;
}
You can also do the same by using the DirectoryInfo instance method. I just faced this problem and I believe this can resolve your problem too.
var fullfilepath = Server.MapPath(System.Web.Configuration.WebConfigurationManager.AppSettings["folderPath"]);
System.IO.DirectoryInfo deleteTheseFiles = new System.IO.DirectoryInfo(fullfilepath);
deleteTheseFiles.Delete(true);
For more details have a look at this link as it looks like the same.
I use the Visual Basic version because it allows you to use the standard dialogs.
https://msdn.microsoft.com/en-us/library/24t911bf(v=vs.100).aspx
Directory.Delete(path,recursive:true);
this code works for delete folder with N subfolder and files in it.

CopyTo() to a directory that doesn't yet exist

I want to copy the file c:\a1\b2\c3\foo.txt to d:\a1\b2\c3\foo.txt. The subdirectories don't exist on the D drive, and if I try to do a direct CopyTo() I'll get an IO exception.
I haven't been able to find any built-in c# function that does the dirty work of creating the missing directories. So I wrote this:
FileInfo file = new FileInfo(#"c:\a1\b2\c3\foo.txt");
DirectoryInfo destDir = new DirectoryInfo(file.DirectoryName.Replace("c:", "d:");
if (!destDir.Exists) // false
CreateDirectory(destDir, null);
file.CopyTo(file.FullName.Replace("c:", "d:"), true);
private void CreateDirectory(DirectoryInfo endDir, Stack<DirectoryInfo> trail)
{
if (trail == null)
{
trail = new Stack<DirectoryInfo>();
trail.Push(endDir);
}
// remove last directory - c:\a1\b2\c3, c:\a1\b2, c:\a1
Match theMatch = Regex.Match(endDir.FullName, #".*(?=\\\w*\Z)");
DirectoryInfo checkDir = new DirectoryInfo(theMatch.ToString());
if (!checkDir.Exists)
{
trail.Push(checkDir);
CreateDirectory(checkDir, trail);
}
else
foreach (DirectoryInfo dir in trail)
Directory.CreateDirectory(dir.FullName);
}
That's pretty involved, and as they like to say on late-night informercials, "There's got to be a better way!"
Question: how would I make the function above move efficient? And am I missing a built-in method that already does everything I'm doing the hard way?
Directory.CreateDirectory(#"c:\foo\bar\baz");
Documented as creating all required directories, and works for me.
Any and all directories specified in
path are created, unless they already
exist or unless some part of path is
invalid. The path parameter specifies
a directory path, not a file path. If
the directory already exists, this
method does nothing.
Or you can just use Directory.CreateDirectory() directly, since it already creates all the intermediate paths.
Strange, I am working with CopyTo and it creates all the subdirectories automatically in the destination location.
My code is as simple as can be:
// file is FileInfo and target is DirectoryInfo
file.CopyTo(target);
A DirectoryInfo instance can create its own path with all the checking you want via destDir.Create():
FileInfo file = new FileInfo(#"c:\a1\b2\c3\foo.txt");
DirectoryInfo destDir = new DirectoryInfo(file.DirectoryName.Replace("c:", "d:");
destDir.Create(); // <-- makes it if it doesn't exist, otherwise noop
var newPath =
Path.Combine(destDir.FullName, Path.GetFileName(file)); // <-- just to be safe...
file.CopyTo(newPath, true);
Found this out here: https://stackoverflow.com/a/2955425/1037948

Categories

Resources