I try to delete one folder with all files inside...But I got an error...I don't know why...the folder is founded with files inside too but when the code try to delete I got the issue...
public static bool DeleteFolder(string FolderName)
{
using (var iso = IsolatedStorageFile.GetUserStoreForApplication())
{
if (iso.DirectoryExists(FolderName))
{
try
{
//get all files in the folder
String[] Files = iso.GetFileNames(FolderName + #"\*");
//delete all files
foreach (var file in Files)
{
iso.DeleteFile(Path.Combine(FolderName, file));
}
//delete the directory
iso.DeleteDirectory(FolderName);
//return true when it's done
if (!iso.DirectoryExists(FolderName))
return true;
}
catch (Exception e)
{
throw new MyException(MyExceptionsMessages.UnknownError + e.Message);
}
}
return true;
}
}
Related
I have a number of USB drives that I want to copy a folder to.
I can't transfer files at the same time, but only one file at a time.
Although I manage to be directed to a different drive each time, but it is not at the same time.
Where am I wrong?
static void Main(string[] args)
{
string path = #"....";
Parallel.ForEach(
DriveInfo.GetDrives(), drive =>
{
if (drive.DriveType == DriveType.Removable)
{
CloneDirectory(path, drive.Name);
}
}
);
}
private static void CloneDirectory(string root, string dest)
{
foreach (var directory in Directory.GetDirectories(root))
{
//Get the path of the new directory
var newDirectory = Path.Combine(dest, Path.GetFileName(directory));
//Create the directory if it doesn't already exist
Directory.CreateDirectory(newDirectory);
//Recursively clone the directory
CloneDirectory(directory, newDirectory);
}
try
{
foreach (var file in Directory.GetFiles(root))
{
try
{
File.Copy(file, Path.Combine(dest, Path.GetFileName(file)), false);
Console.WriteLine(Path.Combine(dest, Path.GetFileName(file)));
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
}
}
I am creating a C# application. This app is deleting temporary folders. But some processes are being used. That's why it can't remove them. And i have to skip those files. I hope you can help.
Code:
// Clearing folder's content (\)
void ClearFolder(string FolderName)
{
try
{
if (Directory.Exists(FolderName))
{
DirectoryInfo dir = new DirectoryInfo(FolderName);
foreach (FileInfo fi in dir.GetFiles())
{
fi.IsReadOnly = false;
fi.Delete();
CleanLog.Items.Add(fi.FullName + " " + "is found and deleted");
}
foreach (DirectoryInfo di in dir.GetDirectories())
{
ClearFolder(di.FullName);
di.Delete();
CleanLog.Items.Add(di.FullName + " " + "is found and deleted");
}
}
else
{
CleanLog.Items.Add(FolderName + " " + "is not found.");
}
}
catch (Exception Error)
{
MessageBox.Show(Error.Message, "Error", MessageBoxButtons.OK);
}
}
// Clearing folder's content (\)
private void Clean_MouseDown(object sender, MouseEventArgs e)
{
// Folder Locations
string Temp = Environment.GetFolderPath(Environment.SpecialFolder.Windows) + #"\Temp"; // Temp
string Temp2 = Path.GetTempPath(); // %Temp%
// Folder Locations
// Clearing folders
ClearFolder(Temp);
ClearFolder(Temp2);
// Clearing folders
}
To achieve this, you can also use try catch for the delete statement like
try
{
fi.Delete();
}
catch
{
//Your message...
}
I'm trying to make this program that will move (cut and paste) all files from one directory (a folder) to another directory. In this example, I'm trying to move all the files that are inside the D:\Source folder (has a few files in it) to C:\Source folder (which has no files in it). When I run the program, I get this error.
http://s13.postimg.org/kuufg0gmu/error.jpg
Here is the full source code:
using System.IO;
namespace FileManager
{
public partial class Form1 : Form
{
string sourceDirectory = "";
//string destinationDirectory = #"C:\Destination";
string date = "";
string[] filePaths;
string destinationPath;
public Form1()
{
InitializeComponent();
}
private void buttonClean_Click(object sender, EventArgs e)
{
// Get source directory
sourceDirectory = textBoxDirectory.Text;
// Get date of files
date = textBoxDate.Text;
// Get file paths
if (Directory.Exists(sourceDirectory))
{
filePaths = Directory.GetFiles(#sourceDirectory, "*", SearchOption.AllDirectories);
foreach (string sourcePath in filePaths)
{
destinationPath = sourcePath.Remove(0, 1).Insert(0, "C");
File.Copy(sourcePath, destinationPath);
//MessageBox.Show(destinationPath);
}
}
else
{
MessageBox.Show("Directory does not exist.");
}
}
}
}
You need to check if destination directory exists than copy files otherwise first create destination directory.
foreach (string sourcePath in filePaths)
{
destinationPath = sourcePath.Remove(0, 1).Insert(0, "C");
if(!Directory.Exists(destinationPath))
Directory.CreateDirectory(destinationpath);
File.Copy(sourcePath, destinationPath);
//MessageBox.Show(destinationPath);
}
Exception clearly states that destinationPath is not valid. Make sure destinationPath exist as shown by #Mairaj then use File.Move to cut-paste. Complete code to move one file. You can your logic of directories to move all the files.
using System;
using System.IO;
class Test
{
public static void Main()
{
string path = #"c:\temp\MyTest.txt";
string path2 = #"c:\temp2\MyTest.txt";
try
{
if (!File.Exists(path))
{
// This statement ensures that the file is created,
// but the handle is not kept.
using (FileStream fs = File.Create(path)) {}
}
// Ensure that the target does not exist.
if (File.Exists(path2))
File.Delete(path2);
// Move the file.
File.Move(path, path2);
Console.WriteLine("{0} was moved to {1}.", path, path2);
// See if the original exists now.
if (File.Exists(path))
{
Console.WriteLine("The original file still exists, which is unexpected.");
}
else
{
Console.WriteLine("The original file no longer exists, which is expected.");
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
}
Find more info here
I have a form with a File Watcher to which he transfers to multiple addresses all video files placed in a folder. What is the best option so that when multiple files are added to even be able to perform each transfer in a thread. Here's an example of my code:
DockingBarTransferEntities context = new DockingBarTransferEntities();
private void fileSystemWatcher1_Changed(object sender, System.IO.FileSystemEventArgs e)
{
IEnumerable<Diretorios> directories = context.Diretorios.ToList();
foreach (var destino in directories)
{
try
{
Transfere(e.FullPath,Path.GetFileName(e.FullPath),destino);
}
catch (Exception ex)
{
textBox1.Text += "Error: " + ex.Message;
}
}
}
public void Transfere(string fullPath, string name, Diretorios diretorio)
{
try
{
if (Directory.Exists(diretorio.Caminho))
{
string fileName = Path.GetFileName(fullPath);
fileName = String.Format("{0}\\{1}", diretorio.Caminho, fileName);
FileInfo arquivo = new FileInfo(fullPath);
arquivo.CopyTo(fileName, true);
}
}
catch (Exception ex)
{
}
}
It should be as simple as this:
Task.Factory.StartNew(() => Transfere(e.FullPath, Path.GetFileName(e.FullPath), destino));
instead of calling Transfere directly.
The following is what i have when i try to delete a folder:
namespace sortfolder
{
class Program
{
static string path = "C:\\Work\\6.70_Extensions\\NightlyBuild\\";
static void Main(string[] args)
{
var di = new DirectoryInfo("C:\\Work\\6.70_Extensions\\NightlyBuild");
foreach (var file in di.GetFiles("*", SearchOption.AllDirectories))
file.Attributes &= ~FileAttributes.ReadOnly;
var files = Directory.GetDirectories(path, "SASE Lab Tools.*");
foreach(var file in files)
Console.WriteLine(file);
foreach(var file in files.OrderByDescending(x=>x).Skip(7))
Console.WriteLine(file);
foreach(var file in files.OrderByDescending(x=>x).Skip(7))
Directory.Delete(file);
}
}
}
As mentioned in the title, i would like to delete this folder along with all its content. How do i go about doing it? Apparently i have IOException # Directory.Delete(file) as it contains files
You missing true Directory.Delete(file,true);
For example
public static void Main()
{
string path = #"c:\MyDir\temp";
try
{
Directory.Delete(path, true);
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
finally {}
}
Directory.Delete has a second parameter which takes a bool = recrusive. Use that overload instead.
http://msdn.microsoft.com/en-us/library/fxeahc5f.aspx