How do I access files on a c$ resource from C# - c#

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.

Related

How to correctly extract the directory from the registry key "ImagePath"?

I am looking for a particular application install location in registry. Since InstallLocation does not have the value I need, I used ImagePath to get the physical path. However I need the directory and not the full path. What I get is:
(string) subkey.GetValue("ImagePath") =
"\"C:\\Program Files (x86)\\Some Folder\\Some Other Folder\\TheApplication.exe\""
Using
Path.GetDirectoryName((string) subkey.GetValue("ImagePath"))
throws the following error.
Illegal characters in path.
Is this due to extra backslashes? I tried removing those with .Replace(#"\\", "\") but no luck.
It's the quotes that are causing Path.GetDirectoryName to throw the exception. You can call Trim on the returned value to remove the surrounding quotes.
string path = ((string)subkey.GetValue("ImagePath")).Trim('"');
string directoryName = Path.GetDirectoryName(path);

"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.

When working with paths to server files, when is it necessary to use back or forward slashes (single or double)?

Regarding the following code sample:
string baseLocation = HttpContext.Current.Server.MapPath("/");
const string templateName = #"//temp//ExportTemplate.xlsx";
const string generatedLocation = #"{0}//temp//{1}";
var fileName = string.Format("Export-{0}.xlsx", DateTime.Now.Date.ToString("yyyy-MM-dd"));
var newFile = String.Format(generatedLocation, baseLocation, fileName);
File.Copy(baseLocation + templateName, newFile, true);
We are using this on a production server and a local dev environment (via a site in IIS). Both are running IIS 7.5. The code works correctly on production, but throws an error in local dev:
Access to the path 'C:\Path\To\Site\//temp//Export-2013-01-29.xlsx' is denied.
The file is created/copied correctly on local dev, but I'm guessing it's erroring out due to the slashes in the path being incorrect. The app pool identity has full access to the 'temp' folder.
This brings up a couple questions:
In this situation, what does the '//' do to path? I understand '\' is the way to escape a backslash, but the '//' doesn't make sense.
Could there be a difference in the configuration of the two environments that makes the generated path work correctly on the production server but fail in my local dev?
The code should be using a \, not / for file paths.
Either
const string templateName = #"\temp\ExportTemplate.xlsx";
or
const string templateName = "\\temp\\ExportTemplate.xlsx";
would work fine. It's surprising the current version of the code works in production,it may be due to that windows is built to allow either forward or back slashes in file paths. (this goes back to DOS days when many of the users were also UNIX users)
In addition, I'd recommend using Path.Combine rather than just concatenating the strings for the file path (this will get help avoid getting extra slashes or forward slashes in paths like "C:\Path\To\Site\\temp\Export-2013-01-29.xlsx"). ex:
File.Copy(Path.Combine(baseLocation, templateName), newFile, true);
// will always give you // ... With the # at the string, it is a verbatim string literal and you do not need to escape characters. Therefore you can use \ to get . If you drop the #, you will need to use \ to get . When you are working with file paths, it is always a backslash(). When working with URL paths, it is always a forward slash(/)

Get version info of a patch file in c#

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?

move zip file using file.copy()

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.

Categories

Resources