Moving files from one location to another - c#

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

Related

Wait for previous function to complete

I'm working on a web installer and one of the things I have currently is
void MoveFiles()
{
lbldlstatus.Text = "Moving Files";
string InstallDirectory = Directory.GetCurrentDirectory() + "/DoxramosRepack-master";
DirectoryInfo d = new DirectoryInfo(InstallDirectory);
foreach(var file in d.GetFiles("*"))
{
try
{
if (File.Exists(file.Name)) {
File.Delete(file.Name);
}
Directory.Move(file.FullName, file.Name);
Cleanup();
}
catch(Exception e)
{
MessageBox.Show(e.ToString());
lbldlstatus.Text = "Repack Installation Failed";
}
}
}
void Cleanup()
{
lbldlstatus.Text = "Cleaning Up Files";
try
{
if (File.Exists("Repack.zip"))
{
File.Delete("Repack.zip");
}
if(Directory.Exists("DoxramosRepack-master"))
{
Directory.Delete("DoxramosRepack-master");
}
lbldlstatus.Text = "Repack Installed Successfully";
}
When I get to Cleanup() I have a System.IO.IOException.
Process cannot access the file Repack.zip because it being used by
another process.
The full code runs
Download->Extract->Move->Cleanup.
I'm not sure what process is being used, but I'm looking to find a way for each process to wait for the previous to finish before starting.
According to extract code below
void Extract()
{
string zipPath = #"Repack.zip";
string extractPath = #".";
try
{
using (ZipFile unzip = ZipFile.Read(zipPath))
{
unzip.ExtractAll(extractPath);
lbldlstatus.Text = "Extracting Files";
MoveFiles();
}
}
catch (ZipException e)
{
MessageBox.Show(e.ToString());
lbldlstatus.Text = "Repack Installation Failed";
}
}
You are calling the move files before you are finish with the zip file. Seeing as the move file method is responsible for calling the clean up function then you should make sure that the zip file is already disposed of before trying to delete it.
void Extract()
{
string zipPath = #"Repack.zip";
string extractPath = #".";
try
{
using (ZipFile unzip = ZipFile.Read(zipPath))
{
unzip.ExtractAll(extractPath);
lbldlstatus.Text = "Extracting Files";
}
MoveFiles();
}
catch (ZipException e)
{
MessageBox.Show(e.ToString());
lbldlstatus.Text = "Repack Installation Failed";
}
}
Clean up should also be called after everything has been moved. Currently the example code is calling it repeatedly in the for loop.
The code which you pasted on pastebin is different from what you have posted here. The code in pastebin never calls cleanup.
Anyways the problem is because you are calling MoveFiles() from within the using block here:
using (ZipFile unzip = ZipFile.Read(zipPath))
{
unzip.ExtractAll(extractPath);
lbldlstatus.Text = "Extracting Files";
MoveFiles();
}
Move it outside the using block.

C# File and Renaming Automatically from 1?

I wrote this code in c# for change location of folder and all sub-folders of this folder. I want to change name of all folders when copy it to destination. for example I want to change name from 1 to .... . how should I change my code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Windows.Forms;
namespace Folder
{
class clssMoveFolder
{
string temppath;
public string StrtxtSource;
public string destDirName;
public void Directorycopy(string sourceDirName, string destDirName, bool cutSubDirs, string strExtension)
{
try
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
// If the source directory does not exist, throw an exception.
if (!dir.Exists)
{
throw new DirectoryNotFoundException("Source directory does not exist or could not be found: " + sourceDirName);
}
FileInfo[] files = dir.GetFiles();
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
//Get the file contents of the directory to copy.
for (int a = 0; a < files.Length; ++a)
{
// Create the path to the new copy of the file.
if (files[a].Extension == "."+strExtension )
{
temppath = Path.Combine(destDirName, files[a].Name);
files[a].MoveTo(temppath);
}
else if (files[a].Extension == strExtension)
{
temppath = Path.Combine(destDirName, files[a].Name);
files[a].MoveTo(temppath);
}
else if (strExtension == "AllFiles")
{
temppath = Path.Combine(destDirName, files[a].Name);
files[a].MoveTo(temppath);
}
else
files[a].Delete();
dir.Refresh();
}
FileInfo[] filesCheck = dir.GetFiles();
if (dirs.Length == 0 && filesCheck.Length == 0 && dir.Name != StrtxtSource)
{
dir.Delete();
}
// If copySubDirs is true, copy the subdirectories.
if (cutSubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
// Copy the subdirectories.
string temppath= Path.Combine(destDirName, subdir.Name);
Directorycopy(subdir.FullName, temppath,cutSubDirs,strExtension);
}
}
}
catch (Exception e)
{
MessageBox.Show(e.ToString());
}
}
}
}
If you just want to rename a file after copying it you could instead directly copy it under a different name. E.g. instead of copying a.txt and rename it to b.txt afterwards, you could just copy the original a.txt as b.txt to the destination directory.
Renaming can be done by using the File.Move method.
File.Move("a.txt", "b.txt");
If you want to be able to do this even if someone else copies files into a directory (e.g. by using the windows explorer or files written by another application), you may want to take a closer look at the FileSystemWatcher. You can use it to monitor changes in a specified directory (optionally including it's subdirectories) and react on these changes.
...
FileSystemWatcher watcher = new FileSystemWatcher();
watcher.Path = #"D:\SomeTestDirectory";
watcher.Filter = "*.*";
watcher.NotifyFilter = NotifyFilters.FileName; // Trigger only on events associated with the filename
watcher.Created += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true; // Starts the "watching"
...
private static void OnChanged(object source, FileSystemEventArgs e)
{
// Do whatever you want here, e.g. rename the file.
Console.WriteLine("File: " + e.FullPath + " " + e.ChangeType);
}

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

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

deleting entire folder including all the files inside

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

Categories