Disposing assembly - c#

I am trying to show the version numbers of both old and new to user then copy the new version. When I was trying copy the file after showing the version information I am getting the following exception
The process cannot access the file 'C:\Auto TEC\Common.dll' because it is being used by another process.
Here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Reflection;
using System.Diagnostics;
namespace copyfile
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string sourceDirectory = #"E:\newversion\Auto TEC";
string targetDirectory = #"C:\Auto TEC";
Copy(sourceDirectory, targetDirectory);
label3.Text = "sucess";
loadAssembyNames();
}
void f2_FormClosed(object sender, FormClosedEventArgs e)
{
this.Close();
}
public static void Copy(string sourceDirectory, string targetDirectory)
{
DirectoryInfo diSource = new DirectoryInfo(sourceDirectory);
DirectoryInfo diTarget = new DirectoryInfo(targetDirectory);
CopyAll(diSource, diTarget);
}
public static void CopyAll(DirectoryInfo source, DirectoryInfo target)
{
// Check if the target directory exists, if not, create it.
if (Directory.Exists(target.FullName) == false)
{
Directory.CreateDirectory(target.FullName);
}
// Copy each file into it's new directory.
foreach (FileInfo fi in source.GetFiles())
{
fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
}
// Copy each subdirectory using recursion.
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories())
{
DirectoryInfo nextTargetSubDir =
target.CreateSubdirectory(diSourceSubDir.Name);
CopyAll(diSourceSubDir, nextTargetSubDir);
}
}
string _errMsg;
//private AssemblyInformation _info;
private void getfilenames(string directoryPath, int location)
{
string[] path = new string[25];
int count = 0;
foreach (string file in System.IO.Directory.GetFiles(directoryPath))
{
path[count] = file;
count++;
}
Assembly asm = null;
for (int i = 0; i < count; i++)
{
try
{
//asm = Assembly.LoadFrom(path[i]);
asm = Assembly.LoadFile(path[i]);
if (asm != null)
{
if (location == 1)
{
listBox1.Items.Add(asm.GetName().Name + asm.GetName().Version.ToString());
}
else
{
listBox2.Items.Add(asm.GetName().Name + asm.GetName().Version.ToString());
}
}
}
catch (Exception err)
{
this._errMsg = err.Message;
}
}
asm = null;
GC.Collect();
}
private void Form1_Load(object sender, EventArgs e)
{
loadAssembyNames();
}
private void loadAssembyNames()
{
listBox1.Items.Clear();
listBox2.Items.Clear();
getfilenames(#"C:\Auto TEC", 1);
getfilenames(#"E:\newversion\Auto TEC", 2);
}
}
}
How do I unload the assembly information from object?

There's no way to unload an individual assembly without unloading all of the appdomains containing it. So you should use different appdomain foreach of your assemblies.
More info :
Unloading an assembly
Assembly Unload? Use AppDomain.Unload instead

Once assembly is loaded it cannot be unloaded.
You have one option to copy the bytes to the memory and then load using Assembly.Load(byte[]). Also you may use FileVersionInfo which is much easier.

You can't unload an assembly once it's loaded into your AppDomain. The only way to accomplish this is to load the assembly in a separate AppDomain, and unload the entire AppDomain.
As soon as you reference an assembly or type from that assembly within your AppDomain, it will be loaded into that AppDomain and not released.

In .Net, if you load the assembly in the same AppDomain as the application, then it's not possible to unload it (this includes loading it for reflection only). If you need to inspect the assembly internals, I recommend using Mono.Cecil (http://www.mono-project.com/Cecil).

I think i am not in time to answer this questions but i had the same problem and for future reference you just need to use "FileVersionInfo.GetVersionInfo"
system.Diagnostics
and thats it, this option will not load the assembly just its information and you will be able to replace the file.

Related

cannot convert from 'System.Management.EnumerationOptions' to 'System.IO.SearchOption

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Microsoft.VisualBasic.FileIO;
using System.Management;
namespace test_code
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderDlg = new FolderBrowserDialog();
//folderDlg.ShowDialog();
if (folderDlg.ShowDialog() != DialogResult.OK)
{
return;
}
// Has different framework dependend implementations
// in order to handle unauthorized access to subfolders
RenamePngFiles(folderDlg.SelectedPath);
}
private void RenamePngFiles(string directoryPath)
{
int fileNameSuffixCounter = 1;
foreach (string originalFullFileName in System.IO.Directory.EnumerateFiles(directoryPath, "*.png", new EnumerationOptions()))
{
// The new file name without path
var newFileName = $"{System.IO.Path.GetFileNameWithoutExtension(originalFullFileName)}#{fileNameSuffixCounter++}{System.IO.Path.GetExtension(originalFullFileName)}";
FileSystem.RenameFile(originalFullFileName, newFileName);
}
}
}
}
Above is my code and I am not sure why i am not able to remove the above error. I tried all sorts of namespace and i cannot of get rid of it. I am using .netframework 4.7.2.
AS you can see all I am trying to do is rename all the files in a folder including subfolder to append with # and a number which keep on increasing depending on the number of files in a folder.
Combined with the comments above, I made the following changes.
Updated:
Modify all png files in the selectedPath.
RenameAllPngFiles(folderDlg.SelectedPath);
The following are custom functions:
Rename all png files :
private void RenameAllPngFiles(string directoryPath) {
RenameCurrentPng(directoryPath);
foreach (var item in GetDirectoryInfos(directoryPath)) {
RenameCurrentPng(item.FullName);
}
}
Rename all png files in the current directory:
private void RenameCurrentPng(string directoryPath) {
int fileNameSuffixCounter = 1;
foreach (string originalFullFileName in Directory.EnumerateFiles(directoryPath, "*.png")) {
// The new file name without path
var newFileName = $"{System.IO.Path.GetFileNameWithoutExtension(originalFullFileName)}#{fileNameSuffixCounter++}{System.IO.Path.GetExtension(originalFullFileName)}";
FileSystem.RenameFile(originalFullFileName, newFileName);
}
}
Get the addresses of all subfolders :
private DirectoryInfo[] GetDirectoryInfos(string directoryPath) {
DirectoryInfo di = new DirectoryInfo(directoryPath);
DirectoryInfo[] directories = di.GetDirectories("*", System.IO.SearchOption.AllDirectories);
return directories;
}
If you have questions about my code, please comment below and I will follow up.

How do I make my progressbar show the progess of a directory being copied [duplicate]

This question already has answers here:
Visual feedback on long running task
(1 answer)
C# WinForm progress bar not progressively increasing
(3 answers)
Closed 3 years ago.
I have a piece of code wich copies a folder to another directory. I wanted to implement a progress bar so the user can see the progress of the files being copied. I've tried some things, but I just cant get it to work.
This is the code I thought would do what I said above, but the progress bar doesn't make any progress, why the folder is actually being copied.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace intChanger
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
string Dirr;
string Dirr2;
int no = 0;
int Count = 0;
int Count2 = 0;
private void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
if (no == 0)
{
no = 1;
Dirr = sourceDirName;
Dirr2 = destDirName;
Count = Directory.GetFiles(Dirr, "*.*", SearchOption.AllDirectories).Length;
Count = 100 / Count;
}
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
DirectoryInfo[] dirs = dir.GetDirectories();
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
Count2 = Count2 + 1;
progressBar1.Value = Count2 * Count;
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
DirectoryCopy(#"C:\Users\Stefan\Downloads\Portable Python 2.7.15 Basic (x64)\Portable Python 2.7.15 x64", #"C:\Users\Stefan\Documents\Backuppers_Backups\Portable Python 2.7.15 x64", true);
MessageBox.Show("Done coppieng", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
I expect the Progress bar to go slowly up, but it doesn't: It stays at 0
However it does actually copy the files
You should put the copy process in a BackgroundWorker and refresh the progress bar from the _bgwCopyOperation_ProgressChanged event.
Because you are processing the copy operation in the GUI thread, you block controls from refreshing.
Try something like this. You still need to modify this a bit to pass the parameters to the _bgwCopyOperation_DoWork event.
private void _bgwCopyOperation_DoWork(object sender, DoWorkEventArgs e)
{
if (no == 0)
{
no = 1;
Dirr = sourceDirName;
Dirr2 = destDirName;
Count = Directory.GetFiles(Dirr, "*.*", SearchOption.AllDirectories).Length;
Count = 100 / Count;
}
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
DirectoryInfo[] dirs = dir.GetDirectories();
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
Count2 = Count2 + 1;
//Update progressbar here
_bgwCopyOperation.ReportProgress(Count2 * Count);
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
private void _bgwCopyOperation_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
The BackgroundWorker is certainly the best approach, it will send all the heavy copy into a separate thread an not keep the GUI thread busy with simple copy.
...but if you are copying small folders, you could try using the Refresh function on the progress bar:
using System;
using System.Threading;
using System.Windows.Forms;
namespace ProgressBat
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
progressBar1.Value = 0;
for (int i = 0; i < 100; i++)
{
progressBar1.Value = i;
progressBar1.Refresh();
Thread.Sleep(50);
}
button1.Enabled = true;
}
}
}
That example will get the progress bar moving correctly.
And it is a one line fix to your code

Enumerate folder/subfolder contents to right-click context menu of system tray application in C#

I'm utilizing the template from https://alanbondo.wordpress.com/2008/06/22/creating-a-system-tray-app-with-c/ for creating a system tray icon that has a right-click context menu.
I'm able to have one of the buttons launch an explorer process that opens to the root of a directory using this function
private void MyApps(object sender, EventArgs e)
{
String currentUser = Environment.UserName.ToString();
Process explorer = new Process();
explorer.StartInfo.FileName = "explorer.exe";
explorer.StartInfo.Arguments = #"C:\Users\" + currentUser + #"\desktop\MyApps";
explorer.StartInfo.WindowStyle = ProcessWindowStyle.Normal;
explorer.Start();
}
What I would rather do is have the system tray icon button, when clicked, expand into a sub-menu that contains the contents of the desired directory, which itself contains browseable sub-folders. Imagine the (pre-Windows 8) Start menu with nested menus and applications; that is the behavior I'd like to mimic.
What I have found thus far are multiple projects people have written to create their own customized Windows Explorer shell, do actually have to go that far in order to dynamically enumerate the contents of the desired folder into the right-click context menu of a system tray icon?
I'm much more comfortable using visual studio forms for .NET applications but from what I have read, there's no way to actually 'hide' the form at launch, so for now I'm using C#
Any advice or suggestions would be appreciated. Thanks!
Edit: Here's the updated code with the suggested method for recursively populating the menu item with the contents of the specified directory. I'm now getting an error that "System.Windows.Forms.MenuItem" does not contain a definition for DropDownItems
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Diagnostics;
using System.IO;
namespace MyTrayApp
{
public class SysTrayApp : Form
{
[STAThread]
public static void Main()
{
Application.Run(new SysTrayApp());
}
private NotifyIcon trayIcon;
private ContextMenu trayMenu;
public SysTrayApp()
{
trayMenu = new ContextMenu();
trayMenu.MenuItems.Add("Exit", OnExit);
trayMenu.MenuItems.Add("My Applications").Click += new EventHandler(MyApps);
trayIcon = new NotifyIcon();
trayIcon.Text = "MyTrayApp";
trayIcon.Icon = new Icon(SystemIcons.Application, 40, 40);
trayIcon.ContextMenu = trayMenu;
trayIcon.Visible = true;
}
protected override void OnLoad(EventArgs e)
{
Visible = false; // Hide form window.
ShowInTaskbar = false; // Remove from taskbar.
base.OnLoad(e);
}
private void OnExit(object sender, EventArgs e)
{
Application.Exit();
}
protected override void Dispose(bool isDisposing)
{
if (isDisposing)
{
trayIcon.Dispose();
}
base.Dispose(isDisposing);
}
private void MyApps(object sender, EventArgs e)
{
String currentUser = Environment.UserName.ToString();
string[] directories = Directory.GetDirectories(#"C:\Users\" + currentUser + #"\desktop\My Applications");
foreach (string dir in directories)
{
string[] subdir = Directory.GetDirectories(dir);
this.trayMenu.MenuItems.Add(dir);
foreach (string sub in subdir)
{
(trayMenu.MenuItems[trayMenu.MenuItems.Count - 1] as MenuItem).DropDownItems.Add(sub);
}
string[] files = Directory.GetFiles(dir);
foreach (string file in files)
{
this.trayMenu.MenuItems.Add(file);
}
}
}
}
}
This is a simple quick test i've made, using a simple ContextMenuStrip. It of course should be recursive, but just to get you on the track:
string[] directories = Directory.GetDirectories(#"D:\descargas");
foreach (string dir in directories)
{
string[] subdir = Directory.GetDirectories(dir);
this.contextMenuStrip1.Items.Add(dir);
foreach(string sub in subdir)
{
(contextMenuStrip1.Items[contextMenuStrip1.Items.Count-1] as ToolStripMenuItem).DropDownItems.Add(sub);
}
string[] files = Directory.GetFiles(dir);
foreach(string file in files)
{
this.contextMenuStrip1.Items.Add(file);
}
}
Edit
As you are using ContextMenu, and using your provided code, you should do something like this:
private void MyApps(object sender, EventArgs e)
{
String currentUser = Environment.UserName.ToString();
string[] directories = Directory.GetDirectories(#"C:\Users\" + currentUser + #"\desktop\My Applications");
foreach (string dir in directories)
{
string[] subdir = Directory.GetDirectories(dir);
MenuItem mi=new MenuItem(dir);
foreach (string sub in subdir)
{
mi.MenuItems.Add(sub);
}
string[] files = Directory.GetFiles(dir);
foreach (string file in files)
{
mi.MenuItems.Add(file);
}
this.trayMenu.MenuItems.Add(mi);
}
}
I haven't tested it, but I think this would do more or less what you want

Can not copy folders in c#

The problem is that when copying the files in the netscan.zip file to the usb.
It unzip all to root.
This is how the files looks in KHtemp folder:
c:\Data\install\ <- Files
c:\Data\info <- Files
c:\Knowhow.exe
But when the copying is done i looks like this on the usb
\knohow.exe
\data\
\intall\
\info\
I can not find out what iam doing wrong.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace KHupdater
{
public partial class Install : Form
{
public Install()
{
InitializeComponent();
Close.Visible = false;
}
// COPY
#region copy
public static void CopyFolder(string sourcePath, string destinationPath)
{
Directory.CreateDirectory(destinationPath);
// Copy files first.
foreach (var sourceFile in Directory.GetFiles(sourcePath))
{
string destFile = Path.Combine(destinationPath, Path.GetFileName(sourceFile));
File.Copy(sourceFile, destFile, true);
}
foreach (var sourceSubPath in Directory.GetDirectories(sourcePath))
{
string destPath = Path.Combine(destinationPath, sourceSubPath.Substring(sourcePath.Length));
CopyFolder(sourceSubPath, destPath);
}
}
#endregion
private void Start_Click(object sender, EventArgs e)
{
Start.Visible = false;
Loadingbar.Visible = true;
string tempfolder = "C:\\KHtemp";
string tempfile = #"c:\KHtemp\Update.zip";
// If the 'tempfolder' exists it will be deleted
if (Directory.Exists(tempfolder))
{
Directory.Delete("c:\\KHtemp", true);
}
Loadingbar.Value = (10);
// Make Folder and download file
if (!Directory.Exists(tempfolder))
{
Directory.CreateDirectory(tempfolder);
}
WebClient webClient = new WebClient();
webClient.DownloadFile("http://67.327.195.57/netscan.zip", #"c:\KHtemp\Update.zip");
Loadingbar.Value = (50);
// Unrar files in to 'tempfolder'
ZipFile.ExtractToDirectory(tempfile, tempfolder);
// Del rar file from 'tempfolder'
File.Delete("c:\\KHtemp\\Update.zip");
// !?
Loadingbar.Value = (70);
// Copy files to USB
var StartupPath = Application.StartupPath;
var root = System.IO.Path.GetPathRoot(StartupPath);
// Copy All files from 'tempfolder' to root of the USB
foreach (var sourceFilePath in Directory.GetFiles(tempfolder))
{
string fileName = Path.GetFileName(sourceFilePath);
string destinationFilePath = Path.Combine(root, fileName);
System.IO.File.Copy(sourceFilePath, destinationFilePath, true);
CopyFolder(tempfolder, root);
}
Loadingbar.Value = (90);
//// Del 'tempfolder'
Directory.Delete("c:\\KHtemp", true);
////
this.Loadingbar.Style = System.Windows.Forms.ProgressBarStyle.Blocks;
// Show message when done
Loadingbar.Value = (100);
label1.Text = "Update is Done";
Close.Visible = true;
}
private void Close_Click(object sender, EventArgs e)
{
var StartupPath = Application.StartupPath;
var root = System.IO.Path.GetPathRoot(StartupPath);
var Knowhowfile = "Knowhow.exe";
var Knowhow = Process.Start(root + Knowhowfile);
Environment.Exit(1);
}
}
}
You need to copy each folder as well - something like this will work:
public static void CopyFolder(string sourcePath, string destinationPath)
{
Directory.CreateDirectory(destinationPath);
// Copy files first.
foreach(var sourceFile in Directory.GetFiles(sourcePath))
{
string destFile = Path.Combine(destinationPath, Path.GetFileName(sourceFile));
File.Copy(sourceFile, destFile, true);
}
foreach(var sourceSubPath in Directory.GetDirectories(sourcePath))
{
string destPath = Path.Combine(destinationPath, Path.GetFileName(sourceSubPath));
CopyFolder(sourceSubPath, destPath);
}
}
You should call CopyFolder(tempFolder, root)
Please note that it is not tested, you need to debug the CopyFolder method to verify e.g. destPath
You need to identify the current item in loop is File or Directory.
If it's a file then write a code of copy and if it's a directory then create it manually by using System.IO.Directory.CreateDirectory("");

how do I copy a folder to a USB? C#

I'm working on a project that will automatically update my USB with some files from my computer.
The program works on start up and monitors for any USB or CD that is plugged into the computer. My program is to then copy some folders and its files to the USB. I am having trouble copying the folders into the USB and would appreciate some help, thanks.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// this section starts the timer so it can moniter when a USB or CD is inserted into
// the computer.
//==================================================================================
private void Form1_Load(object sender, EventArgs e)
{
timer1.Interval = 100;
timer1.Start();
WindowState = FormWindowState.Minimized;
//===================================================================================
}
private void timer1_Tick(object sender, EventArgs e)
{
// this section checks to see if there is a drive type of USB and CDs.
foreach(DriveInfo drive in DriveInfo.GetDrives())
{
if (drive.DriveType == DriveType.Removable)
{
// this part is supposed to copy a folder from the PC and paste it to the USB
//==============================================================================
//==============================================================================
}
if (drive.DriveType == DriveType.CDRom)
{
// same thing but for CDs.
//==============================================================================
//==============================================================================
}
}
}
// this section opens a folderbrowserdialog that the users can use to access their folders
//and put them into a listbox so when a USB or CD is inserted it will copy those files into
// the storage devices.
//==============================================================================
private void button1_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
listBox1.Items.Add(folderBrowserDialog1.SelectedPath);
//==============================================================================
}
}
}
}
Here is how it can be done:
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
Use File.Copy and use the USB drive letter for the destination. For example:
string sourceDir = #"c:\current";
string backupDir = #"f:\archives\2008";
try
{
string[] picList = Directory.GetFiles(sourceDir, "*.jpg");
string[] txtList = Directory.GetFiles(sourceDir, "*.txt");
// Copy picture files.
foreach (string f in picList)
{
// Remove path from the file name.
string fName = f.Substring(sourceDir.Length + 1);
// Use the Path.Combine method to safely append the file name to the path.
// Will overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), true);
}
// Copy text files.
foreach (string f in txtList)
{
// Remove path from the file name.
string fName = f.Substring(sourceDir.Length + 1);
try
{
// Will not overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName));
}
// Catch exception if the file was already copied.
catch (IOException copyError)
{
Console.WriteLine(copyError.Message);
}
}
// Delete source files that were copied.
foreach (string f in txtList)
{
File.Delete(f);
}
foreach (string f in picList)
{
File.Delete(f);
}
}
catch (DirectoryNotFoundException dirNotFound)
{
Console.WriteLine(dirNotFound.Message);
}
please refer to MSDN:
http://msdn.microsoft.com/en-us/library/bb762914.aspx

Categories

Resources