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("");
Related
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.
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
File comes in over EDI as .today. I need to change it to .txt and move it to another folder. Everything works just fine for about 3-5 files, then starts throwing exceptions. I tried handling those, but that doesn't solve the problem. I'm also getting sporadic (filename cannot be null) exceptions as well. I just can't seem to figure this out.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Windows.Forms;
using System.Security.Permissions;
namespace FileConverterService
{
class ConverterService
{
//Configure watcher & input
private FileSystemWatcher _watcher;
public bool Start()
{
_watcher = new FileSystemWatcher(#"C:\FTP_base\temp", "*.today");
_watcher.Created += new FileSystemEventHandler(FileCreated);
_watcher.IncludeSubdirectories = false;
_watcher.EnableRaisingEvents = true;
return true;
}
//Configure output creation and append file name to include .txt extension
[PermissionSet(SecurityAction.Demand, Name = "FullTrust")]
private void FileCreated(object sender, FileSystemEventArgs e)
{
try
{
string dateTime = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string content = File.ReadAllText(e.FullPath);
string upperContent = content.ToUpperInvariant();
var dir = Path.GetDirectoryName(e.FullPath);
var convertedFileName = Path.GetFileName(e.FullPath) + dateTime + ".txt";
var convertedPath = Path.Combine(dir, convertedFileName);
File.WriteAllText(convertedPath, upperContent);
}
catch (IOException f)
{
if (f is IOException)
{
MessageBox.Show("Exception Caught"); //was just testing
}
}
MoveConvert();
}
//Move converted file to EDI processing folder
public static void MoveConvert()
{
try {
string dateTime = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string rootFolderPath = #"C:\FTP_base\temp\";
string moveTo = #"C:\FTP_base\INbound\inbound_" + dateTime + ".txt";
//string moveTo = #"F:\FTP_base\Office Depot\INbound\inbound_" + dateTime + ".txt";
string filesToMove = #"*.txt"; // Only move .txt
string myfile2 = System.IO.Directory.GetFiles(rootFolderPath, filesToMove).FirstOrDefault();
string fileToMove = myfile2;
//moving file
File.Move(fileToMove, moveTo);
MoveOriginal();
}
catch (IOException e)
{
if (e is IOException)
{
MessageBox.Show("File already exists."); //was just testing
}
}
}
public static void MoveOriginal()
{
try {
string dateTime = DateTime.Now.ToString("yyyyMMddHHmmssfff");
string rootFolderPath2 = #"C:\FTP_base\temp\";
string moveTo2 = #"C:\FTP_base\archive\archive_" + dateTime + ".archive";
//string moveTo2 = #"F:\Xcelerator_EDI\OfficeDepot\DataFiles\Inbound\Archive2\archive_" + dateTime + ".archive";
string filesToMove2 = #"*.today"; // Only move .today
string myfile = System.IO.Directory.GetFiles(rootFolderPath2, filesToMove2).FirstOrDefault();
//foreach (string file in fileList)
string fileToMove2 = myfile;
//moving file
File.Move(fileToMove2, moveTo2);
}
catch (IOException e)
{
if (e is IOException)
{
MessageBox.Show("IO Exception Occurred"); //was just testing
}
}
}
//Stop Service control
public bool Stop()
{
_watcher.Dispose();
return true;
}
}
}
Perhaps the files are still in use. The FileSystemWatcher event is raised when a file is created, but the creating process can still be writing to it. See here for a possible solution.
I have this code that backup and restore in C# using MS Access as its database. I finished doing the backup in zip format and now I want to restore the Zipped file. Any help will be much appreciated.
public void BackupDatabase(string dateToday)
{
string dbFileName = "dbCPS.accdb";
string CurrentDatabasePath = Path.Combine(Environment.CurrentDirectory , dbFileName);
string backTimeStamp = Path.GetFileNameWithoutExtension(dbFileName) + "_" + dateToday + ".zip";// +Path.GetExtension(dbFileName);
string destFileName = backTimeStamp;// +dbFileName;
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == DialogResult.OK)
{
string PathtobackUp = fbd.SelectedPath.ToString();
destFileName = Path.Combine(PathtobackUp, destFileName);
//File.Copy(CurrentDatabasePath, destFileName, true);
using (var zip = new ZipFile())
{
zip.AddFile(dbFileName);
zip.Save(destFileName);
}
MessageBox.Show("Backup successful! ");
}
}
private void backupToolStripMenuItem1_Click(object sender, EventArgs e)
{
BackupDatabase(DateTime.Now.ToString("ddMMMyyyy_HH.mm"));
}
public void RestoreDatabase(string restoreFile)
{
string dbFileName = "dbCPS.accdb";
string pathBackup = restoreFile;
string CurrentDatabasePath = Path.Combine(Environment.CurrentDirectory, dbFileName);
File.Copy(pathBackup, CurrentDatabasePath, true);
MessageBox.Show("Restore successful! ");
}
private void restoreToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
openFileDialogBackUp.FileName = "dbCPS";
openFileDialogBackUp.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory + #"Sauvegardes";
if (openFileDialogBackUp.ShowDialog() == DialogResult.OK)
RestoreDatabase(openFileDialogBackUp.FileName);
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
This code extracts the zipped file but I dont know how to do the restore at the same time.
using (ZipFile zip = ZipFile.Read(restoreFile))
{
zip.ExtractAll(CurrentDatabasePath);
}
I've done it! For those who are in need of the code, here it is:
using (ZipFile zip = ZipFile.Read(pathBackup))
{
zip.ExtractAll(Environment.CurrentDirectory, ExtractExistingFileAction.OverwriteSilently);
}
You cannot overwrite directly the database while you are actively using it.
By actively I mean you have an OleDbConnection open on that database.
From your code above it is not possible to understand if you are in this situation, so the first thing to do is to search for all occurences of an OleDbConnection and check if they are closed correctly. If you have a global OleDbConnection that it is kept open for the lifetime of your application (a very bad practice), then you need to close it before trying to overwrite the accdb file
public void RestoreDatabase(string restoreFile)
{
string dbFileName = "dbCPS.accdb";
string extractedFile = Path.GetTempFileName();
string CurrentDatabasePath = Path.Combine(Environment.CurrentDirectory, dbFileName);
using (ZipFile zip = ZipFile.Read(restoreFile))
{
// Extract to a temporary name built by the Framework for you....
zip.ExtractAll(extractedFile);
}
// Now, before copying over the accdb file, you need to be sure that there is no
// open OleDbConnection to this file, otherwise the IOException occurs because you
// cannot change that file while it is actively used by a OleDbConnection
// something like global_conn.Close(); global_conn.Dispose();
File.Copy(extractedFile, CurrentDatabasePath, true);
MessageBox.Show("Restore successful! ");
// and then reopen the connection
}
private void btn_UodateMembers_Click(object sender, EventArgs e)
{
if (!bwUpdateMembers.IsBusy)
{
bwUpdateMembers.RunWorkerAsync();
}
}
private string ExtractZip(FileInfo fi)
{
string extractTo = Path.Combine(fi.DirectoryName, Guid.NewGuid().ToString());
using (ZipFile zip = ZipFile.Read(fi.FullName))
{
foreach (ZipEntry ze in zip)
{
ze.Extract(extractTo, ExtractExistingFileAction.OverwriteSilently);
}
}
return extractTo;
}
public FileInfo GetLatestFile(DirectoryInfo di)
{
FileInfo fi = di.GetFiles()
.OrderByDescending(d => d.CreationTime)
.FirstOrDefault();
return fi;
}
private void bwUpdateMembers_DoWork(object sender, DoWorkEventArgs e)
{
string path = "C:\\Users\\Ghost Wolf\\Desktop\\zip";
DirectoryInfo di = new DirectoryInfo(path);
if (di != null)
{
FileInfo fi = GetLatestFile(di);
string folder = ExtractZip(fi);
MessageBox.Show("Your'e Files Have Been Extracted", "Notice", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
}
}
PLEASE TELL ME IF THIS WORKED FOR YOU!!
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