deleting entire folder including all the files inside - c#

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

Related

How to make Variable within foreach loop exist? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I apologize if this sounds like a ignorant question but I am quite new to C#. I am one error away from getting my program to work:
"the name 'filesInfo' does not exist in the current context"
I am trying to get this variable to exist and attempted at solving this by declaring it outside the foreach loop, but to no avail.
Here is my current script:
public class MyClass
{
public static string src = #"C:\Users\Bold Defiance\Desktop\FolderA";
public static string dst = #"C:\Users\Bold Defiance\Desktop\FolderB";
public static string[] files = System.IO.Directory.GetFiles(src, "*.txt");
public void Move_Modified_Files()
{
foreach (string s in files)
{
string fileName = Path.GetFileName(s);
FileInfo filesInfo = new FileInfo(fileName);
}
try
{
if (filesInfo.LastWriteTime.Date == DateTime.Today.Date)
{
File.Move(src, dst);
Console.WriteLine("Modified files in {0} were moved to {1}", src, dst);
}
else
{
Console.WriteLine("No new or modified files were created today.");
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
}
class Program
{
static void Main(string[] args)
{
MyClass cls = new MyClass();
cls.Move_Modified_Files();
}
}
You are declaring filesInfo within the foreach loop. As such, its scope is restricted to that loop. If you want to use it elsewhere, you have to move it to the corresponding scope:
FileInfo filesInfo;
foreach (string s in files)
{
string fileName = Path.GetFileName(s);
filesInfo = new FileInfo(fileName);
}
try
{
if (filesInfo.LastWriteTime.Date == DateTime.Today.Date)
{
File.Move(src, dst);
Console.WriteLine("Modified files in {0} were moved to {1}", src, dst);
}
else
{
Console.WriteLine("No new or modified files were created today.");
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
That being said, you are currently overriding filesInfo on every iteration of the loop. I imagine that you wanted to check filesInfo for every value of s, so what you actually wanted to do is this:
foreach (string s in files)
{
string fileName = Path.GetFileName(s);
FileInfo filesInfo = new FileInfo(fileName);
try
{
if (filesInfo.LastWriteTime.Date == DateTime.Today.Date)
{
File.Move(src, dst);
Console.WriteLine("Modified files in {0} were moved to {1}", src, dst);
}
else
{
Console.WriteLine("No new or modified files were created today.");
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
Try this:
public void Move_Modified_Files()
{
foreach (string s in files)
{
string fileName = Path.GetFileName(s);
FileInfo filesInfo = new FileInfo(fileName);
try
{
if (filesInfo.LastWriteTime.Date == DateTime.Today.Date)
{
File.Move(src, dst);
Console.WriteLine("Modified files in {0} were moved to {1}", src, dst);
}
else
{
Console.WriteLine("No new or modified files were created today.");
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
}
You declared
FileInfo filesInfo = new FileInfo(fileName);
inside the first loop. When this context ends with the } the variable will disappear.
My guess is that you wanted to do this.
public class MyClass
{
public static string src = #"C:\Users\Bold Defiance\Desktop\FolderA";
public static string dst = #"C:\Users\Bold Defiance\Desktop\FolderB";
public static string[] files = System.IO.Directory.GetFiles(src, "*.txt");
public void Move_Modified_Files()
{
foreach (string s in files)
{
// These values will exist until their enclosing context is closed
// The context starts with the most recent opening bracket {
// So these values, will exist until this loop iterates to the next value
string fileName = Path.GetFileName(s);
FileInfo filesInfo = new FileInfo(fileName);
// Attempt to use the currently selected fileinfo
try
{
if (filesInfo.LastWriteTime.Date == DateTime.Today.Date)
{
File.Move(src, dst);
Console.WriteLine("Modified files in {0} were moved to {1}", src, dst);
}
else
{
Console.WriteLine("No new or modified files were created today.");
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
// The next } bracket below is the one that closes the context mentioned earlier
// When it closes, all values declared in this sub-context will no longer exist.
}
}
}
class Program
{
static void Main(string[] args)
{
MyClass cls = new MyClass();
cls.Move_Modified_Files();
}
}

Rename OST File in C#

I have this code in C# that works fine in some users.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Threading;
namespace Rename_OST
{
class Program
{
static public void killOutlook()
{
try
{
string process = "OUTLOOK";
foreach (Process outLook in Process.GetProcessesByName(process))
{
outLook.Kill();
}
}
catch (Exception) { }
}
static public void startOutlook()
{
try
{
//busca el path del Outlook
Process.Start("OUTLOOK");
}
catch (Exception)
{
Console.WriteLine("Could'n open Outlook. Please start Outlook and press any key.");
Console.ReadKey();
}
}
static public void replaceOutlook()
{
string ostPath = "C:\\Users\\" + Environment.UserName + "\\AppData\\Local\\Microsoft\\Outlook\\";
string ostFile = "Outlook.ost";
string ostNewFile = "Outlook.ost.txt";
try
{
if (!File.Exists(ostPath + ostNewFile))
{
File.Move(ostPath + ostFile, ostPath + ostNewFile);
}
else
{
File.Delete(ostPath + ostNewFile);
File.Move(ostPath + ostFile, ostPath + ostNewFile);
}
}
catch (FileNotFoundException)
{
Console.WriteLine("The OST file was not found.");
Console.ReadKey();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
Console.ReadKey();
}
}
static void Main(string[] args)
{
Console.WriteLine("Closing Outlook client...");
killOutlook();
Console.WriteLine("Replacing OST file name...");
Thread.Sleep(5000);
replaceOutlook();
Thread.Sleep(5000);
Console.WriteLine("Starting Outlook client...");
startOutlook();
}
}
}
The code only works if the file is named outlook.ost. How can I change the code in order that rename the OST file search regardless of the name.
Thanks in advance
Iterate through the files in the directory to check if they're .OST and then rename them.
// GET ALL FILES IN DIRECTORY
string[] fileEntries = Directory.GetFiles(ostPath);
// CHECK EACH FILE
foreach (string fileName in fileEntries)
{
// IS IT AN OST?
if (Path.GetExtension(fileName).ToLower() == ".ost")
{
// RENAME LOGIC HERE, EXAMPLE:
File.Move(fileName, fileName + ".OLD");
}
}
You should be careful hard coding the .OST path like that. Something like the below would be better:
string ostPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), #"Microsoft\Outlook");
Edit
An better example of replaceOutlook(). Still needs work but better illustrates how this works for OP.
static public void replaceOutlook()
{
// OST PATH
string ostPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), #"Microsoft\Outlook");
// LIST OF FILE PATHS IN OST PATH
string[] fileEntries = Directory.GetFiles(ostPath);
try
{
// CHECK EACH FILE PATH
foreach (string fileName in fileEntries)
{
// IS IT AN OST?
if (Path.GetExtension(fileName).ToLower() == ".ost")
{
// TRY AND DELETE OLD FILE, WON'T THROW EXCEPTION IF FILE DOESN'T EXIST
File.Delete(fileName + ".OLD");
// RENAME FILE
File.Move(fileName, fileName + ".OLD");
}
}
}
catch
{
// Blah blah....
}
}

Moving files from one location to another

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

Unable to delete file Exception WP8 Isolated Storage

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

Add strings to listbox in WPF using C# in a thread

I want to display the path of each file when a button is pressed.
What I have right now is a function that iterates through a folder and displays the paths, but only when the function is finished:
public void ProcessDirectory(string targetDirectory)
{
// Process the list of files found in the directory.
try
{
var fileEntries = Directory.GetFiles(targetDirectory);
foreach (var fileName in fileEntries)
{
ProcessFile(fileName);
}
}
catch (Exception e){}
// Recurse into subdirectories of this directory.
try
{
var subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach (string subdirectory in subdirectoryEntries)
ProcessDirectory(subdirectory);
}
catch (Exception e){}
}
public void ProcessFile(string path)
{
myListBox.Items.Add(path);
}
This means that I have to wait before I can do something else.
How can I display the path of a file instantly when the function is running, so i don't have to wait before the function is finished, getting all the paths before displaying in the listbox?
I don't remember where I came across this piece of code, but if you modify your ProcessFile method to something like this it will update your UI after each item is added to your list.
public void ProcessFile(string path)
{
myListBox.Items.Add(path);
myListBox.ScrollIntoView(myListBox.Items[myListBox.Items.Count-1]);
Dispatcher.Invoke(new Action(delegate { }), DispatcherPriority.Background);
}
I think I remember reading somewhere that this "hack" is not recommended due to a number of other problems that might occur, but I can't remember what it was or where I read it. It does the job however.
Maybe someone else can enlighten us about what these problems are...
This makes your method run on another thread:
public void StartProcessThread(string targetDirectory)
{
Thread T = new Thread(new ParameterizedThreadStart(ProcessDirectory));
T.Start(targetDirectory);
}
public void ProcessDirectory(object objTargetDirectory)
{
string targetDirectory = (string)objTargetDirectory;
// Process the list of files found in the directory.
try
{
var fileEntries = Directory.GetFiles(targetDirectory);
foreach (var fileName in fileEntries)
{
ProcessFile(fileName);
}
}
catch (Exception e){}
// Recurse into subdirectories of this directory.
try
{
var subdirectoryEntries = Directory.GetDirectories(targetDirectory);
foreach (string subdirectory in subdirectoryEntries)
ProcessDirectory(subdirectory);
}
catch (Exception e){}
}
public void ProcessFile(string path)
{
Dispatcher.Invoke(new Action(() => {
myListBox.Items.Add(path);
}));
}

Categories