Recursively append directory names to a string - c#

i got a big problem , alright so here is the problem :
I am trying to get the fileinfo from a directory so that i can list it on listview .
When i recursively search for files using that method :
private void Get_Files(string path)
{
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] fi = di.GetFiles();
foreach (FileInfo Info in fi)
{
try
{
Files.Add(Info.FullName);
}
catch(Exception ee)
{
MessageBox.Show(ee.Message);
}
}
foreach (DirectoryInfo DInfo in di.GetDirectories())
{
Get_Files(DInfo.FullName);
}
}
Sometimes the path is longer than 260 Characters , so i am getting that error :
Path is too long and it should not exceed 260 Characters , i have searched over the internet and people said that it has no solution , but i have figured out a solution my self .
Solution : is creating a string and appending each path of the path to that string , so i never get that error when saving the whole path into string.
Think of it as taking the path apart and taking each piece and appending it to the string.
So here is the solution i figured :
List<string> Files = new List<string>();
string completepath = string.Empty;
string current_dire_name = string.Empty;
private void Get_Files(string path)
{
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] fi = di.GetFiles();
foreach (FileInfo Info in fi)
{
try
{
completepath += "\\" + Info.Name;
Files.Add(completepath);
string remove_file_name = completepath;
remove_file_name = remove_file_name.Replace("\\" + Info.Name, "");
completepath = remove_file_name;
}
catch(Exception ee)
{
if(DialogResult.Yes == MessageBox.Show("Error at the Get_Files Method and Error message :\n\n" + ee.Message + "\n\nQuit Application now ?","",MessageBoxButtons.YesNo,MessageBoxIcon.Question))
{
Environment.Exit(0);
}
}
}
foreach (DirectoryInfo DInfo in di.GetDirectories())
{
string remove_folder_name = completepath;
remove_folder_name = remove_folder_name.Replace("\\" + current_dire_name, "");
completepath = remove_folder_name;
current_dire_name = DInfo.Name;
completepath += "\\" + DInfo.Name;
Get_Files(DInfo.FullName);
}
}
Okay , that method saved me , but it generated wrong path , i mean something is not correct , lets say if path should be : C:\Folder1\Folder2\Folder3\file.txt
The generated path is : C:\Folder1\file.txt , something like that ....
I know that the method i did has something wrong especially the recursive appending.
I hope someone figure it with me , so that people can avoid the long path exception.

You're looking for the .Net Long Path library, which uses the \\?\ prefix with the Windows APIs to avoid the restriction entirely.

Related

C# I am trying to move a file from one directory, where I wont know what the name of the file is, to a new directory

I have the below throwing an exception: System.ArgumentException: 'Empty file name is not legal.
Parameter name: sourceFileName'
public bool ArchiveFile()
{
int fileCount = Directory.GetFiles(#"\\company\Archive\IN\InvoiceTest\Inbox\").Length;
DirectoryInfo diFileCheck = new DirectoryInfo(#"\\company\Archive\IN\InvoiceTest\Inbox\");
foreach (var fi in diFileCheck.GetFiles())
{
string strSourceFile = Path.GetFileName(#"\\company\Archive\\IN\InvoiceTest\Inbox\");
string strDestination =Path.Combine(#"\\company\ArchiveIN\InvoiceTest\Archive\", strSourceFile);
File.Move(strSourceFile, strDestination);
}
if (fileCount==0)
{
string strMessage = "No file found in directory: \n\n";
MessageBox.Show(strMessage, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
return false;
}
else
{
return true;
}
}
Your problem is here:
foreach (var fi in diFileCheck.GetFiles())
{
string strSourceFile = Path.GetFileName(#"\\company\Archive\\IN\InvoiceTest\Inbox\");
string strDestination = Path.Combine(#"\\company\ArchiveIN\InvoiceTest\Archive\", strSourceFile);
File.Move(strSourceFile, strDestination);
}
Your fi is a FileInfo object, but you are not using it. Instead of using Path.GetFileName, use fi.Name.
See FileInfo
This reads all files from a source directory, and moves them to a target directory:
var filePaths = Directory.GetFiles("Source"); // get file paths from folder 'Source'
foreach (var filePath in filePaths)
{
var fileName = Path.GetFileName(filePath); // get only the name of the file
var targetPath = Path.Combine("Target", fileName); // create path to target directory 'Target' (including file name)
File.Move(filePath, targetPath); // move file from source path to target path
}

Accessing USB Drives from 'Computer'

I'm trying to copy files over from the desktop to a USB drive programmatically. However, when trying to run this code, I am geting an error stating that part of the path could not be found:
if (dr == DialogResult.Yes)
{
string selected = comboBox1.GetItemText(comboBox1.SelectedItem);
string filePath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string filefolder = #"\UpgradeFiles";
string fileLocation = filePath + filefolder;
if (!Directory.Exists(fileLocation))
{
Directory.CreateDirectory(fileLocation);
}
else if (Directory.Exists(fileLocation))
{
DirectoryInfo di = new DirectoryInfo(fileLocation);
FileInfo[] fileList = di.GetFiles();
foreach (FileInfo file in fileList)
{
string DrivePath = Environment.GetFolderPath(
Environment.SpecialFolder.MyComputer);
string CopyToDrive = comboBox1.Text;
file.CopyTo(DrivePath + CopyToDrive, false);
}
}
}
The combobox contains the selected drive letter. Am I approaching this wrong when trying to add "computer\driveletter"?
Your File.CopyTo(DrivePath + CopyToDrive, false) should be:
File.CopyTo(CopyToDrive + File.Name, false);
but with a bit of syntactic sugar like using Path.Combine or String.Format instead of just "+".
The issue is that File.CopyTo requires both the directory AND filename of the end location, when you're just providing the directory. This can be seen in the documentation for the method call here: https://msdn.microsoft.com/en-us/library/f0e105zt(v=vs.110).aspx

Deleting a specific folder and it's files ASP.NET

Alright so I'm having a bit of an issue here. I'm trying to delete a specific folder inside another folder on my webserver using ASP.NET (C#) The folder being deleted is based on a textbox.
The directory is like this
/images/folderx
folderx = txtDelFolder.Text;
The problem is that everything I try deletes every single thing inside the images folder. I'm guessing that it is not recognizing my folder in the filepath
string path = #"\httpdocs\images\ +
txtDelFolder.Text;
I have also tried
string path = #"\httpdocs\images\ +
txtDelFolder.Text + "\";
Tried all this with both single '\' and double '\'
Would appreciate any help on this
Also where it says <directfilepath> I actually have the filepath typed out, just didn't want to share that here.
****edit****
string path = Server.MapPath("~/imagestest/" + txtEditTitle.Text);
if(Directory.Exists(path))
{
DeleteDirectory(path);
}
}
}
private void DeleteDirectory(string path)
{
foreach(string filename in Directory.GetFiles(path))
{
File.Delete(filename);
}
foreach(string subfolders in Directory.GetDirectories(path))
{
Directory.Delete(subfolders, true);
}
}
Try this:
private void DeleteFiles(string folder)
{
string path=Server.MapPath("~/httpdocs/images/" + folder);
string[] files=Directory.GetFiles(path, "*", SearchOption.AllDirectories);
foreach (string file in files)
{
File.Delete(file);
}
//then delete folder
Directory.Delete(path);
}
try this one :
public void DeleteFolder(string folderPath)
{
if (!Directory.Exists(folderPath))
return;
// get the directory with the specific name
DirectoryInfo dir = new DirectoryInfo(folderPath);
try
{
foreach (FileInfo fi in dir.GetFiles())
fi.Delete();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Don't see why this wouldn't work:
public static bool DeleteDirectory(string input)
{
if (Directory.Exists(input))
{
Directory.Delete(input, true);
return !Directory.Exists(input);
}
else
return true;
}
string thePath = Server.MapPath(#"~/images/");
thePath = Path.Combine(Path.GetFullPath(thePath), txtInput.Text);
if(DeleteDirectory(thePath))
Console.WriteLine("YAY");
else
Console.WriteLine("BOO");

System.UnauthorizedAccessException when getting files

I've asked a very similar question before here. But that was about getting directories, and this is about files. And these codes are a bit different from each other. Ever since I've been trying to convert this to make it look like the answer on my old question, I haven't been able to make it work.
string[] files = Directory.GetFiles(ScanPath, "*.*", System.IO.SearchOption.AllDirectories);
DateTime From = DateTime.Now.AddHours(-24);
DateTime To = DateTime.Now;
foreach (string name in files)
{
FileInfo file = new FileInfo(name);
string fullname = file.FullName;
if (file.LastWriteTime >= From & file.LastWriteTime <= To && file.Length >= ScanSize)
Console.WriteLine(file.FullName + " ; " + "last changed at " + " ; " + file.LastWriteTime.ToString());
}
I've been getting the same errors as I explained in the other question. Because I don't know where to put the code of the foreach in a recursion. Since it's not an enumeration but a Directory.GetFiles().
The error occurs with:
Directory.GetFiles(ScanPath, "*", SearchOption.AllDirectories);
because this gets all the files of the directories at once. But if I remove it, it only gets the files in the given path, without any of the files in the subdirectories. So I was told to apply recursion.
I am the administrator of the system and I plan to run this on the entire data drive. D:\
I'm hoping anyone here knows a good example.
Your app could not have access rights to some folders, for others you can use the following code:
void DiscoverDirs(string where, List<string> files, Func<FileInfo, bool> filter)
{
try
{
var di = new DirectoryInfo(where);
files.AddRange(di.EnumerateFiles().Where(filter).Select(x => x.FullName));
foreach (var dir in Directory.GetDirectories(where))
{
DiscoverDirs(dir, files, filter);
}
}
catch
{
// no access fo this dir, ignore
}
}
Usage:
DateTime From = DateTime.Now.AddHours(-24);
DateTime To = DateTime.Now;
var ScanSize = 5*1024*1024;
var list = new List<string>();
DiscoverDirs(#"C:\", list,
file => file.LastWriteTime >= From & file.LastWriteTime <= To && file.Length >= ScanSize);
foreach (string name in list)
{
FileInfo file = new FileInfo(name);
string fullname = file.FullName;
Console.WriteLine(file.FullName + " ; " + "last changed at " + " ; " + file.LastWriteTime.ToString());
}
You might be getting "UnauthorizedAccessException" while accessing the some of the system directories.List of the directory causing the problems are directories which are actually just redirection to other directory.
May be you can tried out the following code if it helps-
try
{
foreach (String file in Directory.GetFiles(directoryName, pattern, SearchOption.TopDirectoryOnly))
{
// do stuff
}
catch (UnauthorizedAccessException uae)
{
//handle
}
catch (Exception e)
{
//handle
}
Alternative:
string[] directories = Directory.GetDirectories(ScanPath);
foreach (string directory in directories)
{
string[] filesinCurrentDirectory = Directory.GetFiles(directory, "*.*", System.IO.SearchOption.AllDirectories);
foreach (string file in filesinCurrentDirectory)
{
MessageBox.Show(file);
}
}

This code taken from microsoft is only copying the text files in the main directory not sub-directories

Taken from: http://msdn.microsoft.com/en-us/library/dd383571.aspx
I've modified it to copy files, but even when I had it exactly as microsofts example, it still is ignoring the text file I placed in a subdirectory as a test...I'm dying to know what is going on here since I thought "SearchOption.AllDirectories" took care of that...
{
string sourceDirectory = #"C:\Users\root\Desktop\bms 2013\bms 2013";
string archiveDirectory = #"C:\Users\root\Desktop\test";
try
{
var txtFiles = Directory.EnumerateFiles(sourceDirectory, "*.txt", SearchOption.AllDirectories);
foreach (string currentFile in txtFiles)
{
string fileName = currentFile.Substring(sourceDirectory.Length + 1);
File.Copy(currentFile, Path.Combine(archiveDirectory, fileName));
}
}
catch (Exception)
{
// Console.WriteLine(e.Message);
}
}

Categories