i used DirectoryInfo to get files from a folder.
but let say the directory to the folder does not exist
i want a message that says ("directory not found")
DirectoryInfo dinfo = new DirectoryInfo(#"C:\Users\nour\Desktop\Gedaan");
FileInfo[] Files = dinfo.GetFiles("*.DOCX");
foreach (FileInfo file in Files)
{
LB2.Items.Add(file.Name);
}
Use Exists method of DirectoryInfo class to check to check whether directory exists or not.
DirectoryInfo dinfo = new DirectoryInfo(#"C:\Users\nour\Desktop\Gedaan");
if(dinfo.Exists)
{
//your code
}
The file-system can change under your feet, so it's generally better to make an attempt with the file-system and take appropriate corrective measures if you encounter an exception.
So instead of testing with dinfo.Exists then crossing your fingers that the same situation persists on the next few lines, just go ahead and try, then mop up any mess:
DirectoryInfo dinfo = new DirectoryInfo(#"C:\Users\nour\Desktop\Gedaan");
FileInfo[] files;
try
{
files = dinfo.GetFiles("*.DOCX");
}
catch(DirectoryNotFoundException)
{
Console.WriteLine("ouch");
}
after all, any hardened code will need to catch this exception anyway, even if you believe that some microseconds ago the directory existed.
I think you can just do this:
DirectoryInfo dinfo = new DirectoryInfo(#"C:\Users\nour\Desktop\Gedaan");
if (!dinfo.Exists) // <---- check existence here
{
// your message here
}
else
{
// rest of your code here...
FileInfo[] Files = dinfo.GetFiles("*.DOCX");
foreach (FileInfo file in Files)
{
LB2.Items.Add(file.Name);
}
}
Related
I have a .NET webform that is displaying files found in a directory in a listView. This is the code for the display:
private void files()
{
try
{
DirectoryInfo dinfo = new DirectoryInfo(label2.Text);
FileInfo[] Files = dinfo.GetFiles("*.doc");
foreach (FileInfo file in Files)
{
listView1.Items.Add(file.Name);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
label2.Text contains the directory that houses the files. What I need is for a second listView to display a list of documents housed in another directory to display if the file does not appear in the first list view.
The second directory contains templates where as the first directory contains completed documents. The names are different in each directory, but they are similar. For example a completed document displayed in the first listView may be called DEFECT1_AA09890.doc. It's template may be called 05DEFECT.doc.
It is easy enough to display the contents of the template directory using this code:
private void templateDocuments()
{
string path = #"\\directoryname\foldername";
try
{
DirectoryInfo dinfo = new DirectoryInfo(path);
FileInfo[] Files = dinfo.GetFiles("*.doc");
foreach (FileInfo file in Files)
{
listView2.Items.Add(file.Name);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
But this does not compare contents and display based on the results.
Long story short, I want to display the contents of a directory in a listView, compare it to the contents of another directory, and display in a second listView what does not appear in the first.
Any help would be much appreciated.
Cheers.
Before adding file names to listView2, you need to check whether you already added them to listView1. One way of doing that is to store the files in listView1 in a HashSet<string>, then checking that before adding to listView2. Something like this should work:
private void filesAndTemplates()
{
string path = #"\\directoryname\foldername";
HashSet<string> files = new HashSet<string>();
try
{
DirectoryInfo dinfo = new DirectoryInfo(label2.Text);
FileInfo[] Files = dinfo.GetFiles("*.doc");
foreach (FileInfo file in Files)
{
files.Add(file.Name);
listView1.Items.Add(file.Name);
}
dinfo = new DirectoryInfo(path);
Files = dinfo.GetFiles("*.doc");
foreach (FileInfo file in Files)
{
if (files.Contains(file.Name))
{
continue; // We already saw this file
}
listView2.Items.Add(file.Name);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
EDIT
If you want inexact matching, you need to reduce the file name to its essence -- remove any decorations, which in your case looks to be one (or both) of
Leading digits
Underscore followed by whatever
The essence of 01hello_world.doc would thus be hello.
Regex should fit the bill quite nicely -- although the exact definition of the regular expression would depend on your exact requirements.
Define the Regex and a transformation method somewhere suitable:
private static readonly Regex regex = new Regex(
#"[0-9]*(?<core>[^_]+)(_{1}.*)?", RegexOptions.Compiled);
private static string Transform(string fileName)
{
int extension = fileName.LastIndexOf('.');
if (extension >= 0)
{
fileName = fileName.Substring(0, extension);
}
Match match = regex.Match(fileName);
if (match.Success)
{
return match.Groups["core"].Value;
}
return fileName;
}
Then modify the original method to transform the filename before adding files to the HashSet and before checking for their presence:
DirectoryInfo dinfo = new DirectoryInfo(label2.Text);
FileInfo[] Files = dinfo.GetFiles("*.doc");
foreach (FileInfo file in Files)
{
files.Add(Transform(file.Name)); // Here!
listView1.Items.Add(file.Name);
}
dinfo = new DirectoryInfo(path);
Files = dinfo.GetFiles("*.doc");
foreach (FileInfo file in Files)
{
if (files.Contains(Transform(file.Name))) // Here!
{
continue;
}
listView2.Items.Add(file.Name);
}
Note the two calls to Transform.
I am trying to create a directory and subdirectories and copy files from on one location to another location. The following code works but it doesn't create a parent directory(10_new) if there are sub directories. I am trying to copy all the contents(including subdirectories) from "c:\\sourceLoc\\10" to "c:\\destLoc\\10_new" folder. If "10_new" doesn't exist then I should create this folder. Please assist.
string sourceLoc = "c:\\sourceLoc\\10";
string destLoc = "c:\\destLoc\\10_new";
foreach (string dirPath in Directory.GetDirectories(sourceLoc, "*", SearchOption.AllDirectories))
{
Directory.CreateDirectory(dirPath.Replace(sourceLoc, destLoc));
if (Directory.Exists(sourceLoc))
{
//Copy all the files
foreach (string newPath in Directory.GetFiles(sourceLoc, "*.*", SearchOption.AllDirectories))
File.Copy(newPath, newPath.Replace(sourceLoc, destLoc));
}
}
From looking at your code, you never check for the existence of the parent folders. You jump to getting all the child folders first.
if (!Directory.Exists(#"C:\my\dir")) Directory.CreateDirectory(#"C:\my\dir");
Here is how to copy all files in a directory to another directory
This is taken from http://msdn.microsoft.com/en-us/library/cc148994.aspx
string sourcePath = "c:\\sourceLoc\\10";
string targetPath = "c:\\destLoc\\10_new";
string fileName = string.Empty;
string destFile = string.Empty;
// To copy all the files in one directory to another directory.
// Get the files in the source folder. (To recursively iterate through
// all subfolders under the current directory, see
// "How to: Iterate Through a Directory Tree.")
// Note: Check for target path was performed previously
// in this code example.
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
// Use static Path methods to extract only the file name from the path.
fileName = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(s, destFile, true);
}
}
else
{
Console.WriteLine("Source path does not exist!");
}
Recursive Directory/Sub-directory
public class RecursiveFileSearch
{
static System.Collections.Specialized.StringCollection log = new System.Collections.Specialized.StringCollection();
static void Main()
{
// Start with drives if you have to search the entire computer.
string[] drives = System.Environment.GetLogicalDrives();
foreach (string dr in drives)
{
System.IO.DriveInfo di = new System.IO.DriveInfo(dr);
// Here we skip the drive if it is not ready to be read. This
// is not necessarily the appropriate action in all scenarios.
if (!di.IsReady)
{
Console.WriteLine("The drive {0} could not be read", di.Name);
continue;
}
System.IO.DirectoryInfo rootDir = di.RootDirectory;
WalkDirectoryTree(rootDir);
}
// Write out all the files that could not be processed.
Console.WriteLine("Files with restricted access:");
foreach (string s in log)
{
Console.WriteLine(s);
}
// Keep the console window open in debug mode.
Console.WriteLine("Press any key");
Console.ReadKey();
}
static void WalkDirectoryTree(System.IO.DirectoryInfo root)
{
System.IO.FileInfo[] files = null;
System.IO.DirectoryInfo[] subDirs = null;
// First, process all the files directly under this folder
try
{
files = root.GetFiles("*.*");
}
// This is thrown if even one of the files requires permissions greater
// than the application provides.
catch (UnauthorizedAccessException e)
{
// This code just writes out the message and continues to recurse.
// You may decide to do something different here. For example, you
// can try to elevate your privileges and access the file again.
log.Add(e.Message);
}
catch (System.IO.DirectoryNotFoundException e)
{
Console.WriteLine(e.Message);
}
if (files != null)
{
foreach (System.IO.FileInfo fi in files)
{
// In this example, we only access the existing FileInfo object. If we
// want to open, delete or modify the file, then
// a try-catch block is required here to handle the case
// where the file has been deleted since the call to TraverseTree().
Console.WriteLine(fi.FullName);
}
// Now find all the subdirectories under this directory.
subDirs = root.GetDirectories();
foreach (System.IO.DirectoryInfo dirInfo in subDirs)
{
// Resursive call for each subdirectory.
WalkDirectoryTree(dirInfo);
}
}
}
}
Before doing File.Copy, check to make sure the folder exists. If it doesn't create it.
This function will check if a path exists, if it doesnt, it will create it. If it fails to create it, for what ever reason, it will return false. Otherwise, true.
Private Function checkDir(ByVal path As String) As Boolean
Dim dir As New DirectoryInfo(path)
Dim exist As Boolean = True
If Not dir.Exists Then
Try
dir.Create()
Catch ex As Exception
exist = False
End Try
End If
Return exist
End Function
Remember, all .Net languages compile down to the CLR (common language runtime) so it does not matter if this is in VB.Net or C#. A good way to convert between the two is: http://converter.telerik.com/
It is impossible to copy or move files with C# in windows 7.
It will instead create a file of zero bytes.
I am writing a class (based on a class library) that creates a RAMDisk, and every X minutes I need to backup the contents of the RAMDisk to a physical location due to volatility. It was suggested to use CopyFileEx, as apparently the .NET file copy methods do not work.
For some reason I am getting an Invalid Arguements error when trying to use CopyFileEx though. I am assuming that I can still use the rest of the .NET methods in this function, but could just use some help fixing/cleaning it up a bit.
public static void CopyDirectoryVSS(string sourcePath, string targetPath)
{
// Check if the target directory exists, if not, create it.
if (Directory.Exists(targetPath) == false)
{
Directory.CreateDirectory(targetPath);
}
// Copy each file into it’s new directory.
foreach (string dir in Directory.GetDirectories(sourcePath))
{
foreach (string file in Directory.GetFiles(dir, "*.*"))
{
Console.WriteLine(#"Copying {0}\{1}", targetPath, file);
CopyFileEx(file, Path.Combine(target, file), null, 0, 0, 0);
}
}
// Copy each subdirectory using recursion.
DirectoryInfo sourceDir = new DirectoryInfo(#sourcePath);
DirectoryInfo TargetDir = new DirectoryInfo(targetPath);
foreach (DirectoryInfo diSourceSubDir in sourceDir.GetDirectories())
{
DirectoryInfo nextTargetSubDir = TargetDir.CreateSubdirectory(diSourceSubDir.Name);
CopyDirectory(diSourceSubDir, nextTargetSubDir);
}
}
Check out the answer here: I'm guessing that copy solution would be cleaner and you're essentially doing the same thing:
Copying Files Recursively
I'm very new to C#. My boss asked me to wrote some code using listview as a file browser. I tried it and it seems it works. This code is to open the files from your drives and display it on the listView. It's very simple. I also made an additional function where one can clear the displayed items in the listView. I would like to add additional feature, where I can also open the directory and not only the files.
By the way, here is the sample of my code:
private void btnOpen_Click(object sender, EventArgs e)
{
string strSelectedPath;
folderBrowserDialog1.ShowDialog();
strSelectedPath = folderBrowserDialog1.SelectedPath;
label1.Text = strSelectedPath;
DirectoryInfo di = new DirectoryInfo(strSelectedPath);
FileInfo[] files = di.GetFiles();
foreach (FileInfo file in files)
{
listView1.Items.Add(file.Name);
}
}
private void btnClear_Click(object sender, EventArgs e)
{
listView1.Items.Clear();
label1.Text="";
}
Could you please show me how?
If I understand your question correctly (you want to list not only the files in the selected directory, but also the sub-directories), you will want to look into the GetDirectories method of the DirectoryInfo class.
You could do something like this, perhaps:
DirectoryInfo di = new DirectoryInfo(strSelectedPath);
// first list sub-directories
DirectoryInfo[] dirs = di.GetDirectories();
foreach (DirectoryInfo dir in dirs)
{
listView1.Items.Add(dir.Name);
}
// then list the files
FileInfo[] files = di.GetFiles();
foreach (FileInfo file in files)
{
listView1.Items.Add(file.Name);
}
Update: I would suggest that you move the above code into a separate method that takes a string parameter for the path (something like ListDirectoryContents(string path)). In this method you can start with clearing the items from the list view, setting the label text and then adding new content as above.
This method can be called from your btnOpen_Click method, passing folderBrowserDialog1.SelectedPath in the path parameter.
I usually try to keep my event handlers as small as possible, preferably not performing any real work but rather just call some other method that does the work. This opens up a bit more for triggering the same functionality from other places.
Say for instance that your application can take a path as a command line parameter, then it will be cleaner code just calling ListDirectoryContents with the path from the command line than perhaps duplicating the same behaviour in your form.
Full code example of that approach:
private void btnOpen_Click(object sender, EventArgs e)
{
string path = BrowseForFolder();
if (path != string.Empty)
{
ListDirectoryContent(path);
}
}
private string BrowseForFolder()
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == DialogResult.OK)
{
return fbd.SelectedPath;
}
return string.Empty;
}
private void ListDirectoryContent(string path)
{
label1.Text = path;
listView1.Items.Clear();
DirectoryInfo di = new DirectoryInfo(path);
// first list sub-directories
DirectoryInfo[] dirs = di.GetDirectories();
foreach (DirectoryInfo dir in dirs)
{
listView1.Items.Add(dir.Name);
}
// then list the files
FileInfo[] files = di.GetFiles();
foreach (FileInfo file in files)
{
listView1.Items.Add(file.Name);
}
}
The upsides of this code is that you can reuse the method BrowseForFolder whenever you need to browse for a folder, since it simply returns the selected path and is not connected to what the path will be used for. Similarly, the ListDirectoryContent method is completely unaware of from where the path parameter comes; it may come from the folder browser, it may come from the command line or anywhere else.
If you focus on having your methods performing only their "core task", relying on input parameters for any additional information that they need you will get code that is easier to reuse and maintain.
When it comes to event handlers (such as btnOpen_Click), I like to see them as triggers; they trigger things to happen, but the don't really do a lot themselves.
The DirectoryInfo class contains a GetDirectories method, as well as a GetFiles method. See your original code sample below, modified to add directories:
private void btnOpen_Click(object sender, EventArgs e)
{
string strSelectedPath;
folderBrowserDialog1.ShowDialog();
strSelectedPath = folderBrowserDialog1.SelectedPath;
label1.Text = strSelectedPath;
DirectoryInfo di = new DirectoryInfo(strSelectedPath);
FileInfo[] files = di.GetFiles();
DirectoryInfo[] directories = di.GetDirectories();
foreach (DirectoryInfo directory in directories)
{
listView1.Items.Add("Directory " + directory.Name);
}
foreach (FileInfo file in files)
{
listView1.Items.Add(file.Name);
}
}
I believe this is what you want?
DirectoryInfo[] directories = di.GetDirectories();
foreach (DirectoryInfo directory in directories)
{
listView1.Items.Add(directory.Name);
}
I need to Copy folder C:\FromFolder to C:\ToFolder
Below is code that will CUT my FromFolder and then will create my ToFolder.
So my FromFolder will be gone and all the items will be in the newly created folder called ToFolder
System.IO.Directory.Move(#"C:\FromFolder ", #"C:\ToFolder");
But i just want to Copy the files in FromFolder to ToFolder.
For some reason there is no System.IO.Directory.Copy???
How this is done using a batch file - Very easy
xcopy C:\FromFolder C:\ToFolder
Regards
Etienne
This link provides a nice example.
http://msdn.microsoft.com/en-us/library/cc148994.aspx
Here is a snippet
// To copy all the files in one directory to another directory.
// Get the files in the source folder. (To recursively iterate through
// all subfolders under the current directory, see
// "How to: Iterate Through a Directory Tree.")
// Note: Check for target path was performed previously
// in this code example.
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
// Use static Path methods to extract only the file name from the path.
fileName = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(s, destFile, true);
}
}
there is a file copy.
Recreate folder and copy all the files from original directory to the new one
example
static void Main(string[] args)
{
DirectoryInfo sourceDir = new DirectoryInfo("c:\\a");
DirectoryInfo destinationDir = new DirectoryInfo("c:\\b");
CopyDirectory(sourceDir, destinationDir);
}
static void CopyDirectory(DirectoryInfo source, DirectoryInfo destination)
{
if (!destination.Exists)
{
destination.Create();
}
// Copy all files.
FileInfo[] files = source.GetFiles();
foreach (FileInfo file in files)
{
file.CopyTo(Path.Combine(destination.FullName,
file.Name));
}
// Process subdirectories.
DirectoryInfo[] dirs = source.GetDirectories();
foreach (DirectoryInfo dir in dirs)
{
// Get destination directory.
string destinationDir = Path.Combine(destination.FullName, dir.Name);
// Call CopyDirectory() recursively.
CopyDirectory(dir, new DirectoryInfo(destinationDir));
}
}
Copying directories (correctly) is actually a rather complex task especially if you take into account advanced filesystem techniques like junctions and hard links. Your best bet is to use an API that supports it. If you aren't afraid of a little P/Invoke, SHFileOperation in shell32 is your best bet. Another alternative would be to use the Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory method in the Microsoft.VisualBasic assembly (even if you aren't using VB).
yes you are right.
http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.aspx
has provided copy function ..
or you can use another function
http://msdn.microsoft.com/en-us/library/ms127960.aspx
You'll need to create a new directory from scratch then loop through all the files in the source directory and copy them over.
string[] files = Directory.GetFiles(GlobalVariables.mstrReadsWellinPath);
foreach(string s in files)
{
fileName=Path.GetFileName(s);
destFile = Path.Combine(DestinationPath, fileName);
File.Copy(s, destFile);
}
I leave creating the destination directory to you :-)
You're right. There is no Directory.Copy method. It would be a very powerful method, but also a dangerous one, for the unsuspecting developer. Copying a folder can potentionaly be a very time consuming operation, while moving one (on the same drive) is not.
I guess Microsoft thought it would make sence to copy file by file, so you can then show some kind of progress information. You could iterate trough the files in a directory by creating an instance of DirectoryInfo and then calling GetFiles(). To also include subdirectories you can also call GetDirectories() and enumerate trough these with a recursive method.
A simple function that copies the entire contents of the source folder to the destination folder and creates the destination folder if it doesn't exist
class Utils
{
internal static void copy_dir(string source, string dest)
{
if (String.IsNullOrEmpty(source) || String.IsNullOrEmpty(dest)) return;
Directory.CreateDirectory(dest);
foreach (string fn in Directory.GetFiles(source))
{
File.Copy(fn, Path.Combine(dest, Path.GetFileName(fn)), true);
}
foreach (string dir_fn in Directory.GetDirectories(source))
{
copy_dir(dir_fn, Path.Combine(dest, Path.GetFileName(dir_fn)));
}
}
}
This article provides an alogirthm to copy recursively some folder and all its content
From the article :
Sadly there is no built-in function in System.IO that will copy a folder and its contents. Following is a simple recursive algorithm that copies a folder, its sub-folders and files, creating the destination folder if needed. For simplicity, there is no error handling; an exception will throw if anything goes wrong, such as null or invalid paths or if the destination files already exist.
Good luck!
My version of DirectoryInfo.CopyTo using extension.
public static class DirectoryInfoEx {
public static void CopyTo(this DirectoryInfo source, DirectoryInfo target) {
if (source.FullName.ToLower() == target.FullName.ToLower())
return;
if (!target.Exists)
target.Create();
foreach (FileInfo f in source.GetFiles()) {
FileInfo newFile = new FileInfo(Path.Combine(target.FullName, f.Name));
f.CopyTo(newFile.FullName, true);
}
foreach (DirectoryInfo diSourceSubDir in source.GetDirectories()) {
DirectoryInfo nextTargetSubDir = target.CreateSubdirectory(diSourceSubDir.Name);
diSourceSubDir.CopyTo(nextTargetSubDir);
}
}
}
And use like that...
DirectoryInfo d = new DirectoryInfo("C:\Docs");
d.CopyTo(new DirectoryInfo("C:\New"));