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
Related
goal: we are not talking about files, but about folders. if the desired folder, which is specified in the array of strings, is available on the desktop, then we need to get subdirectories and paths to this folder, if the desired folder is not on the desktop, then the search for this folder has already been performed in appdata, and then the same thing, if the folder is present, then we get subdirectories and paths to this folder.
string[] directory = new string [] {#"folder1/", #"folder3/", }
foreach (string sPath in directory)
{
string Path;
if (sPath.Contains("folder1"))
{
Path = Desktop + sPath;
}
else
{
Path = Appdata + sPath;
}
there is an if (sPath.Contains("folder1"))
I intended the string Path to first take the Path = "Desktop + sPath" logic to return the names of the subdirectories of the folder1 folder
if (Directory.Exists(Path)) foreach (string folder in Directory.GetDirectories(Path))
{
Console.WriteLine(folder);
this code does not work for me = (if you delete a folder from the desktop, which, for example, was present, then the search from another place that is specified in the code is not carried out( how to fix the situation?
string Path;
if (sPath.Contains("folder1"))
{
Path = Desktop + sPath;
}
else
{
Path = Appdata + sPath;
}
full code
string [] directory = new string [] {#"folder1/", #"folder3/", }
foreach (string sPath in directory)
{
string sFullPath;
if (sPath.Contains("folder1"))
{
sFullPath = Desktop + sPath;
}
else
{
sFullPath = Appdata + sPath;
}
if (Directory.Exists(sFullPath)) foreach (string folder in Directory.GetDirectories(sFullPath))
{
Console.WriteLine(folder);
}
}
First of all we should come to terms. To be "available on the desktop" is to be a subfolder of
// Have a look at
// Environment.SpecialFolder.CommonDesktopDirectory
// Environment.SpecialFolder.DesktopDirectory
// as well
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
then we can manipulate with directory array:
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string[] directory = new string [] {#"folder1/", #"folder3/", };
foreach (string sPath in directory) {
if (Directory.Exists(Path.Combine(desktop, sPath))) {
// available on the desktop
}
else if (Directory.Exists(Path.Combine(appData, sPath))) {
// available on the AppData
}
else {
// not exists
}
}
I need to copy a bunch of files from an Android phone to the PC.
It doesn't work the normal way, the PC is super slow and crashes all the time for some reason.
I want to copy it file by file.
My problem is that if I use Directory.GetFiles("Path") or DirectoryInfo.GetFiles("Path") it does add the persistant Datapath to the path for some reason and I get this error message:
DirectoryNotFoundException: Could not find a part of the path 'D:\GameDev\CopyProgram\Dieser PC\HTC One M9\Interner gemeinsamer Speicher'.
The actual path is only "Dieser PC\HTC One M9\Interner gemeinsamer Speicher", is there any way to do that?
//there is an input field where you can enter the paths
(copy it from the explorer)
[SerializeField]
private string copyFrom = "Dieser PC\HTC One M9\Interner gemeinsamer Speicher";
[SerializeField]
private string copyTo = "C:\Users\Nutzer\Desktop\Neuer Ordner";
private bool running = false;
public void Copy()
{
if(running == true)
{
return;
}
running = true;
//Start
//Get all items from folder
DirectoryInfo d = new DirectoryInfo(copyFrom);
FileInfo[] Files = d.GetFiles();
foreach (FileInfo file in Files)
{
string currentFile = file.DirectoryName + "/" + file.Name;
string copyFile = copyTo + "/" + file.Name;
try
{
if (file == null)
continue;
File.Copy(currentFile, copyFile, true);
}
catch (Exception)
{
throw;
}
}
//End
running = false;
}
I searched through the internet and could not find a solution, please help!
Thanks!
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
}
I have a listBox1 that should display all the files on my desktop, i have used the following method to do so
string filepath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
DirectoryInfo path = new DirectoryInfo(filepath);
foreach (var file in path.GetFiles())
{
listBox1.Items.Add("File : " + file.Name);
}
It works but for some reason it doesn't display some shortcuts, it displays a few shortcuts but most of them are not displayed. I have no idea why this is happening
You are probably missing the shortcuts in the "All Users" desktop:
string filepath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
DirectoryInfo path = new DirectoryInfo(filepath);
foreach (var file in path.GetFiles())
{
listBox1.Items.Add("File : " + file.Name);
}
// Get files in the "common" desktop
filepath = Environment.GetFolderPath(Environment.SpecialFolder.CommonDesktopDirectory);
path = new DirectoryInfo(filepath);
foreach (var file in path.GetFiles())
{
listBox1.Items.Add("File : " + file.Name);
}
You can refactor to combine the common code if that works.
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.