Move a file from one directory to another - c#

I created a zip file/folder with DotNetZip. I'm trying to move that file from the original directory/folder to another, e.g. My Documents. So far I have done the following, but it gives me an error saying that it could not find part of the path.
private static void Move()
{
try
{
Directory.Move(#"Debug\Settings.zip", IO.Paths.Enviroment.MyDocuments);
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}
UPDATE:
So I've played with it a bit and laughed not because I fixed it but because it's weird. I used both File.Move() and Directory.Move() and changed both.Move(#"Debug\Settings.zip",...); to both.Move(#"Settings.zip",...); and then get get an an error saying Cannot create a file when that file already exists.

While it may seem strange to use Directory.Move to move a file, (I'd use File.Move instead), Jean-Philippe Leclerc points out that it will work.
The problem is with the path Debug\Settings.zip:
All relative paths are relative to the working directory. By default the working directory is the folder in which the assembly (your program) is executed, and while debugging that is the bin\Debug subfolder of your project. So your path Debug\Settings.zip is expanded to a path like:
C:\..\MyProject\bin\Debug\Debug\Settings.zip
This is probably not what you meant. You meant just "Settings.zip".
The fact that it's a ZIP is irrelevant.

Use System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) to get your MyDocuments path.

could not find part of the path - The error seems like the Relative Path to your file Settings.Zip is not a valid path!
You need to use File.Move, Directory.Move will move the entire content of the Directory to different folder.
File.Move : Only moves the file to a specified location
private static void Move()
{
try
{
File.Move(#"Debug\Settings.zip", System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
}
catch(Exception ex)
{
Console.WriteLine(ex.Message);
}
}

Fixed! The issues were first the "Debug\Settings.zip" should have been "Settings.zip" or #"Settings.zip" and finally destination should not just be System.IO.File.Move(#"Settings.zip", System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop)); but System.IO.File.Move(#"Settings.zip", System.Environment.GetFolderPath(System.Environment.SpecialFolder.Desktop) + #"\Settings.zip"); Basically, add the file name and the extension of the file at the end of the destination string.

Related

Directory.Move(SourcePath, Destinationpath ) is failing in c#

I believed this to be really simple but somehow i am making a mistake.I am trying to copy one folder to another location
Directory.Move(SourcePath, Destinationpath )
This expression is failing. The exception thrown is "cannot create file that already exists"
Well, you say you want to "copy one folder to another".
Directory.Move(), doesn't copy: as its name implies, it moves a directory. Take at look at the documentation on how to copy files:
.Net 4.0 (see here for an asynchronous approach)
.Net 4.5 (see here for an asynchronous approach)
The Move call is failing because a directory or file in the move operation exists at the specified location (as the exception noted). In order to fix this you need to ensure that no file or directory exists at the destination. The easiest way is to first delete that path
Do not run this function unless you are OK with unconditionally deleting data at DestinationPath.
static void MyMove(string sourcePath, string destPath) {
try {
Directory.Delete(destPath, recursive: true);
} catch {
// Don't care if this fails. If the file didn't exist, great, if the
// file can't be deleted will still get an error in Move. Just try
// Move at this point
}
Directory.Move(sourcePath, destPath);
}

"Could not find a part of the path" error message

I am programming in c# and want to copy a folder with subfolders from a flash disk to startup.
Here is my code:
private void copyBat()
{
try
{
string source_dir = "E:\\Debug\\VipBat";
string destination_dir = "C:\\Users\\pc\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\Programs\\Startup";
if (!System.IO.Directory.Exists(destination_dir))
{
System.IO.Directory.CreateDirectory(destination_dir);
}
// Create subdirectory structure in destination
foreach (string dir in Directory.GetDirectories(source_dir, "*", System.IO.SearchOption.AllDirectories))
{
Directory.CreateDirectory(destination_dir + dir.Substring(source_dir.Length));
}
foreach (string file_name in Directory.GetFiles(source_dir, "*.*", System.IO.SearchOption.AllDirectories))
{
File.Copy(file_name, destination_dir + file_name.Substring(source_dir.Length), true);
}
}
catch (Exception e)
{
MessageBox.Show(e.Message, "HATA", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
I got an error:
Could not find a part of the path E:\Debug\VipBat
The path you are trying to access is not present.
string source_dir = "E:\\Debug\\VipBat\\{0}";
I'm sure that this is not the correct path. Debug folder directly in E: drive looks wrong to me. I guess there must be the project name folder directory present.
Second thing; what is {0} in your string. I am sure that it is an argument placeholder because folder name cannot contains {0} such name. So you need to use String.Format() to replace the actual value.
string source_dir = String.Format("E:\\Debug\\VipBat\\{0}",variableName);
But first check the path existence that you are trying to access.
There's something wrong. You have written:
string source_dir = #"E:\\Debug\\VipBat\\{0}";
and the error was
Could not find a part of the path E\Debug\VCCSBat
This is not the same directory.
In your code there's a problem, you have to use:
string source_dir = #"E:\Debug\VipBat"; // remove {0} and the \\ if using #
or
string source_dir = "E:\\Debug\\VipBat"; // remove {0} and the # if using \\
Is the drive E a mapped drive? Then, it can be created by another account other than the user account. This may be the cause of the error.
I had the same error, although in my case the problem was with the formatting of the DESTINATION path. The comments above are correct with respect to debugging the path string formatting, but there seems to be a bug in the File.Copy exception reporting where it still throws back the SOURCE path instead of the DESTINATION path. So don't forget to look here as well.
-TC
Probably unrelated, but consider using Path.Combine instead of destination_dir + dir.Substring(...). From the look of it, your .Substring() will leave a backlash at the beginning, but the helper classes like Path are there for a reason.
There can be one of the two cause for this error:
Path is not correct - but it is less likely as CreateDirectory should create any path unless path itself is not valid, read invalid characters
Account through which your application is running don't have rights to create directory at path location, like if you are trying to create directory on shared drive with not enough privileges etc
File.Copy(file_name, destination_dir + file_name.Substring(source_dir.Length), true);
This line has the error because what the code expected is the directory name + file name, not the file name.
This is the correct one
File.Copy(source_dir + file_name, destination_dir + file_name.Substring(source_dir.Length), true);
We just had this error message occur because the full path was greater than 260 characters -- the Windows limit for a path and file name. The error message is misleading in this case, but shortening the path solved it for us, if that's an option.
I resolved a similar issue by simply restarting Visual Studio with admin rights.
The problem was because it couldn't open one project related to Sharepoint without elevated access.
This could also be the issue: Space in the folder name
Example:
Let this be your path:
string source_dir = #"E:\Debug\VipBat";
If you try accessing this location without trying to check if directory exists, and just in case the directory had a space at the end, like :
"VipBat    ", instead of just "VipBat" the space at the end will not be visible when you see in the file explorer.
So make sure you got the correct folder name and dont add spaces to folder names. And a best practice is to check if folder exists before you keep the file there.

C# WPF - Printing all files in directory that has ".xml" format - "could not find part of the path c#"

First of all - i googled the problem, and nothing good related seemed to come up.
Also it will probably seem to you that this question is a newbie one (and i must say i never had this problem when printing files in a directory.
I am pretty new to WPF in C#.
so..
I am having problems to Print all files in directory that has ".xml" format
Here is my code to print the files in a directory (I am not talking about Recursive dirs and files print):
private void Load_ToolboxItems(string dirPath, string os, string version)
{
try
{
foreach (string command in Directory.GetFiles(dirPath, "*.xml"))
{
//load commands by OS compatibility
MessageBox.Show(command);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This is my window load event:
private void Window_Loaded(object sender, RoutedEventArgs e)
{
MessageBox.Show("Combined " + System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName), #"\data\Windows\xp\"));
MessageBox.Show(System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName));
Load_ToolboxItems(System.IO.Path.Combine(System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName), #"\data\Windows\xp\"), "Windows", "XP");
}
Those are the outputs i get when running the program:
1st messagebox- "Combined \data\Windows\xp\"
2nd messagebox-
C:\Users\Din\Din\Programming\Webs\Ended Projects\LogicalArm\Products\Visual Command Line\Visual_Command_Line-wpf_net3.5c_vs2010\Visual_Command_Line\bin\Release
3rd messagebox- "could not find part of the path 'C:\data\Windows\xp'."
This is where the exe starts from:
C:\Users\Din\Din\Programming\Webs\Ended Projects\LogicalArm\Products\Visual Command Line\Visual_Command_Line-wpf_net3.5c_vs2010\Visual_Command_Line\bin\Release
foreach (String file in Directory.GetFiles(dirPath))
{
if (Path.GetExtension(file) == ".xml")
MessageBox.Show(file);
}
Not sure if your underlying issues is you are not getting the exact path you want, however the above should give you what you want from a listing of XML files stance.
Remove the \ from \data\windows\xp (the first \ that is). Also be careful because your path is getting long. There is a 260 character limit.
Path.Combine() know the directory separator character to use, so when you use it, the second parameter should not start with a .
huh,
it always happens to me..
five minutes after i ask a question and after a long search i some-how find the problem myself..
I had problem with the path -_-
thanks for trying to help by the way

Managing temporary files in a small .NET program

My question is about handling temporary files in a small .NET program. This program/utility just does the following with two URLs:
Download each URL to a string (WebClient.DownloadString).
Save each string to a temporary file.
Call WinMerge (Process.Start) to diff the two files (in read-only mode for both files).
I currently have the Simplest Thing That Could Possibly Work:
save URL1 to windows/temp/leftFileToDiff.txt
save URL2 to windows/temp/rightFileToDiff.txt.
This works great - as WinMerge only needs to run in Read Only mode the files can be overwritten by running my program multiple times and nothing bad happens.
However, I would now like to change the temporary file names to something meaningful (related to the URL) so that I can see which is which in the WinMerge view. I also want to clean these files up when they are no longer needed. What are my options for this?
My next simplest idea is to have a specified folder where these are stored and just to zap this every time my program exits. Is there a better/more elegant/standard way?
Thanks.
Create a Guid-based folder under the user's temp area and use that?
string path = Path.Combine(Path.GetTempPath(),
Guid.NewGuid().ToString("n"));
Directory.CreateDirectory(path);
try
{
// work inside path
}
finally
{
try { Directory.Delete(path, true); }
catch (Exception ex) {Trace.WriteLine(ex);}
}

FileInfo compact framework 3.5 - cannot find file

I am using the FileInfo class. However, the file info cannot find the file.
The file is called log4Net.config and I have added it to my project. I have set the properties to build action = 'Content' and copy output = 'copy always'
When I run the following code:
FileInfo logfileInfo = new FileInfo("Log4Net.config");
if (!logfileInfo.Exists)
{
Console.WriteLine("Cannot find file: " + logfileInfo.FullName);
return;
}
else
{
XmlConfigurator.Configure(logfileInfo);
}
Exists is always false. The exception is: Could not find file 'Log4Net.config'.
I have checked on my PDA and the Log4Net.config has been copied the PDA and is in the same directory as the executable. So not sure why it cannot find it.
Just some extra info the configure method expects a FileInfo as a parameter.
Am I doing something wrong.
Many thanks for any advice,
Steve
You have to point to the root of your project. FileInfo points to the root of the OS not the root of the exe. So you should change the code like this :
FileInfo logfileInfo = new FileInfo(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + #"\Log4Net.config");
A file not found exception is also thrown when the program does not have the security permission to access the file, so perhaps that's the case?
btw, there's a contradiction in your Post: First you say the file is called "logPDA.config", then it's suddenly called "Log4Net.config". Just to make sure, is the file always named the same?
You are assuming that the Program Folder is the current directory. Afaik that is not the case. You can investigate starting with System.IO.Directory.GetCurrentDirectory()
string logIOFilePath =
Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase),
"Log4Net.config");

Categories

Resources