I am trying to move a file from server \\abc\\C$\\temp\\coll.zip to another server
\\def\\c$\\temp.
I am trying to use File.Copy(source,destination).
But I am getting the error in source path saying: Couldn't find the part of the path.
I am not sure what is wrong with the source path.
You could use a C# # Verbatim and also use checks in the code like this:
string source = #"\\abc\C$\temp\coll.zip";
string destination = #"\\def\c$\temp\coll.zip";
string destDirectory = Path.GetDirectoryName(destination)
if (File.Exists(source) && Directory.Exists(destDirectory)) {
File.Copy(source, destination);
}
else {
// Throw error or alert
}
Make sure that your "\" characters are escaped if you are using C#. You have to double the backslashes or prefix the string literal with #, like this:
string fileName = #"\\abc\C$\temp\coll.zip";
or
string fileName = "\\\\abc\\C$\\temp\\coll.zip";
looks like you need two backslashes at the beginning:
\\abc\C$\temp\coll.zip
\\def\c$\temp
Make sure you are using a valid UNC Path. UNC paths should start with \ not just . You should also consider using System.IO.File.Exists(filename); before attempting the copy so you can avoid the exception altogether and so your app can handle the missing file gracefully.
Hope this helps
It could be the string you are using for the path. If it is exactly as you have entered here I believe you need double backslashes. "\\" before the server name.
I always use network shares for that kind of work, but UNC path's should be available too.
Don't forget that you need to escape your string when you use \'s. Also, UNC paths most of the time start with a double .
Example:
\\MyComputerName\C$\temp\temp.zip
Actually I missed # before the two strings.The source and the destination path.
That is why it was giving error.
Related
This is very common thing but i am very confused to get around this.
Taking file path as command line argument in c#.
If i give input "F:\\" then this works perfect.
But when i give input "F:\" it gives output like F:".
I know this is because of backslash escape character.
But my problem is how to get around this without modifying user input because logically user input is correct.
Is it possible without modifying user input get correct path in this situation?
I also know that there is # character which can be used.
But as i said this is command line argument so the string is already in variable.
I also read some blogs but still i remain unable to resolve my problem.
C# Command-Line Parsing of Quoted Paths and Avoiding Escape Characters
EDIT :Actually my program is to list all the files inside directory so i am first checking for Directory.Exists(command line arguments) and then getting list of all the files if directory exist.
Ok so in that case when user gives Command line argument as i shown above logically the drive exist but just because of escape character it returns false.
Just think about printing the command line argument as follow.
class Program
{
static void Main(string[] args)
{
Console.WriteLine("{0}", args[0]);
Console.Read();
}
}
I am having very less knowledge of c# thanks for helping.
Im not sure why your having a problem here. In M$ Windows, a directory can be specified with or without a back-slash so all of these are correct: c: and c:\ and c:\media and c:\media\. This is the same for Directory.Exists(path) and other functions like Directory.GetFiles(path).
Ths following is a very simple app to list directory files and in my environment it works regardless of whether I put a slash on the end. So c:\media\ gives me all my media files.
class Program
{
static void Main(string[] args)
{
string path = args[0];
Console.WriteLine("trying path: " + path);
if (Directory.Exists(path))
Directory.GetFiles(path).ToList().ForEach(s => Console.WriteLine(s));
else
Console.WriteLine("path not found");
}
}
One thing to note is that in visual studio, when using the debugger such as Quick Watch, it will show the escape character with backslashs. So if user enters c:\media\ the string will be stored as c:\media\ but when you quick watch the path in VS you'll see c:\\media\\; look deeper with the Text Visualisation feature and you'll see the path correctly shown as c:\media\.
You should use Path class and specifically Path.GetFullPath method to get correct full path.
class Program
{
static void Main(string[] args)
{
string path = Path.GetFullPath(args[0]);
Console.WriteLine("trying path: " + path);
if (Directory.Exists(path)){
var files = Directory.GetFiles(path);
foreach (var file in files) Console.WriteLine(file);
}
else
Console.WriteLine("path doesn't exist");
}
}
UPD. Paths with spaces should be passed in quotes. Or you should concat all your command line arguments, if path is the only input.
Use Environment.GetCommandLineArgs(). It will clean up the path.
See this link for more info: http://msdn.microsoft.com/en-us/library/system.environment.getcommandlineargs(v=vs.110).aspx
Well, if I understand correctly. You can use string.Format . There are overload methods that could help you without modifying much user input.
Sample code:
string[] inputs = ...
string output = string.Format("F:\\{0}\\{1}", inputs[0], inputs[1]);
C# interprets \ as an escape character. So \" is interpreted as "
Possible way to fix it (if you are sure that there is no " inside arguments:
string a = args[0].Replace('"', '\\');
I think your over thinking this. Logically that isnt valid input. \ is an escape character on the command prompt just as it is in c# inside of a string. What you have entered ("F:\") is an invalid value and it IS on the user to correct. The user is saying at this point that they want the quote.
Note that when you pass the filename in parameters, you need to have the access rights in the directory where file is placed, otherwise some parts of your application might fail unexpectedly and it might took you much time to figure out what's wrong there.
var args1 = Environment.GetCommandLineArgs().Skip(1);
if (args1 != null && args1.Count() > 0)
{
//do stuff
}
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.
I'm using an example like this:
System.IO.File.Copy("\\host\c$\folder\file.end", "c:\file.end", true);
But I'm only getting a DirectoryNotFoundException with the description
Could not find a part of the path '\host\c$\folder\file.end'
What do I have to do to access files on a DRIVE$ resource? I have administrative privileges on the machine.
Try using a verbatim string for the path
System.IO.File.Copy(#"\\host\c$\folder\file.end", #"c:\file.end", true);
or escape the slashes
System.IO.File.Copy("\\\\host\\c$\\folder\\file.end", "c:\\file.end", true);
Try:
System.IO.File.Copy(#"\\host\c$\folder\file.end", #"c:\file.end", true);
Because as you can see from exception path is not well formatted. You need to escape \ symbol.
Try
System.IO.File.Copy(#"\\host\c$\folder\file.end", #"c:\file.end", true);
Force a string literal.
I am uploading a .msi file using fileupload control to a central location. Now i need to get version info of this file. I am using the following code.
FileVersionInfo patchFile = FileVersionInfo.GetVersionInfo(completeFilePath)
completeFilePath is the full path of the uploaded file. This code breaks and throws file not found exception.however, if i look down in the physical directory,file exists there.
Am i missing something or will i have to download this uploaded file again to some temp location and then extract version info from this file.
Second option i had was to get version info before uploading the file. In this case i am not able to get complete path of this patch file as fileupload control just gives the fileName and not the complete location.
Please suggest how to proceed.
I think the problem is in how to define "completeFilePath"
Remember that if the completeFilePath is a non-literal string then you must escape the special characters.
For example: [string filePath = "C:\\Windows\\FolderName\\FileName.txt";]
(notice the escape character ()
Another option is to use the literal string which enables you to use the special characters without having to use the escape character. An example is:
[string filePath = #""C:\Windows\FolderName\FileName.txt"";]
If this still doesn't work then could you please post how you are inputting this?
In a WinApp I am simply trying to get the absolute path from a Uri object:
Uri myUri = new Uri(myPath); //myPath is a string
//somewhere else in the code
string path = myUri.AbsolutePath;
This works fine if no spaces in my original path. If spaces are in there the string gets mangled; for example 'Documents and settings' becomes 'Documents%20and%20Setting' etc.
Any help would be appreciated!
EDIT:
LocalPath instead of AbsolutePath did the trick!
This is the way it's supposed to be. That's called URL encoding. It applies because spaces are not allowed in URLs.
If you want the path back with spaces included, you must call something like:
string path = Server.URLDecode(myUri.AbsolutePath);
You shouldn't be required to import anything to use this in a web application. If you get an error, try importing System.Web.HttpServerUtility. Or, you can call it like so:
string path = HttpContext.Current.Server.URLDecode(myUri.AbsolutePath);
It's encoding it as it should, you could probably UrlDecode it to get it back with spaces, but it's not "mangled" it's just correctly encoded.
I'm not sure what you're writing, but to convert it back in asp.net it's Server.UrlDecode(path). You also might be able to use LocalPath, rather than AbsolutePath, if it's a Windows app.
Just use uri.LocalPath instead
Uri also has a couple of static methods - EscapeDataString and EscapeUriString.
Uri.EscapeDataString(uri.AbsolutePath) also works
Use HttpUtility:
HttpUtility.UrlDecode(uri.AbsolutePath)