problem in using path.combine statement in c# - c#

string targetPath = #"C:\Program Files\saadhvi\SetupSafetyPADUniversal\";
string createDatabasesScriptFilePath = Path.Combine(targetPath, "\\EADBScripts\\CreateDatabases.sql");
i am getting the value of createDatabasesScriptFilePath is \EADBScripts\CreateDatabases.sql
but i expected it would be C:\Program Files\saadhvi\SetupSafetyPADUniversal\EADBScripts\CreateDatabases.sql
what is the wrong with my code?

Here is why your code is returning the 2nd path (copied from MSDN help) -
If path2 does not include a root (for example, if path2 does not start with a separator character or a drive specification), the result is a concatenation of the two paths, with an intervening separator character. If path2 includes a root, path2 is returned.

Remove the first \ from the string "\EADBScripts\CreateDatabases.sql"
I'm not completely sure of the reason, but a I guess Path.Combine wants as second parameter a relative path, and a relative Path does not start with a \.

Remove the initial backslash from "\EADBScripts..." in the second argument.

string targetPath = #"C:\Program Files\saadhvi\SetupSafetyPADUniversal\";
string createDatabasesScriptFilePath;
createDatabasesScriptFilePath= Path.Combine(targetPath, "EADBScripts\\CreateDatabases.sql");

Related

C# Path.Combine is not using AppData location

I'm trying to access the AppData folder to create/delete directories as needed but using Path.Combine is yielding only half the desired path. Here's what I have:
string sPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string test = Path.Combine(sPath, #"\Microsoft\Windows\Start Menu\SkillControl\");
The test string is in place of a Directory.CreateDirectory which is the next line (when working). Here are the results of debugging these lines:
sPath: "C:\\Users\\[user]\\AppData\\Roaming"
test: "\\Microsoft\\Windows\\Start Menu\\SkillControl\\"
I was expecting "test" to result in the full path:
C:\\Users\\[User]\\AppData\\Roaming\\Microsoft\\Windows\\Start Menu\\SkillControl\\
but it seems to ignore the combine function. Can anyone work out why?
To clarify before it's asked, sPath is just a way for me to confirm if Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) was pulling the correct location which it is, I get the same results when doing
Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
#"Microsoft\Windows\Start Menu\SkillControl\"));
Your second path is an absolute path - it starts with a backslash. The method is behaving as documented:
If path2 contains an absolute path, this method returns path2.
Just remove the leading backslash and it should be fine.
string sPath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string test = Path.Combine(sPath, #"Microsoft\Windows\Start Menu\SkillControl\");

How to handle whitespaces in paths in command line parameters

I have the problem with whitespaces in my console application. My application is crashing because of not allowed chararcters.
My application is expecting an argument which is a path of the filesystem. So it will be called like this
myProg.exe "D:\tmp\with whitespace\"
With that information I want to create a file in the given folder, but this is not possible because of not allowed char.
String pdfName = "foobar.pdf
String datapath = args[0];
String targetJobFile = datapath + pdfName + ".txt";
I can see in the debugger that the targetJobFile value is
"D:\tmp\with whitespace\"foobar.pdf.txt
And there i receive the exception.
Thanks
You need to remove the quotes from the argument, so before using it, use Trim:
String realArg = args[0].Trim('"');
You already have the \ that Path.Combine would give you; but if you don't want your users to have to enter it, using Path.Combine is a good way to get the path separator character into your string.
Why not just check for existence of " character and replace them before making the full path like
datapath = datapath.Replace("\"","");
String targetJobFile = datapath + pdfName;
You can go one step ahead and use Path.GetInvalidPathChars() which will return all invalid characters not allowed in path names and remove it from your path as follows -
modifiedPathName = new Regex(string.Format("[{0}]", Regex.Escape(new string(Path.GetInvalidPathChars())))).Replace(PathName, replaceChar);

c# illegal character in file path

Hey guys I have this piece of code that will first store a path in a variable, check if that path exists, if not create it. then take that path and add my file name to it.
Here is the code
appData = string.Format("{0}{1}\"", controller.Server.MapPath("~/App_Data/"), Guid.NewGuid().ToString());
if (!Directory.Exists(appData))
Directory.CreateDirectory(appData);
filePath = string.Format("{0}\"{1}", appData, model.File.FileName);
model.File.SaveAs(filePath);
data.Add("attachment", filePath);
But when it gets to the SaveAs function it states
Illegal character in path
AppDath = C:\Users\Ben\Documents\Team Foundation Server\Team
Projects\Shared\Orchard
1.6\Orchard\src\Orchard.Web\App_Data\392216b5-32ad-41f4-82bf-e074b13f25df\"
Any idea why?
use Path.Combine
filePath = Path.Combine(appData, model.File.FileName);
same to create appData path
appData = Path.Combine(controller.Server.MapPath("~/App_Data"), Guid.NewGuid().ToString());
Use
filePath = string.Format(#"{0}\"{1}", appData, model.File.FileName);
The # char show the compiler that the string doesn't have any backslashed characters.
Normaly, you use the \ prefix in some special chars, like \n means a newline. You string has a \, so the compiler tries to resolve it with the next char in the string.
Another way is to escape the backslash with the second one, like this:
filePath = string.Format(#"{0}\\"{1}", appData, model.File.FileName);

Unsupported format while using the correct format

Im getting a "NotSupportedExeption was unhandled by user code - the specified path format is not supported" error, even thou I use a string as is requered.
string path = folder + "/" + filename;
fileByte = File.ReadAllBytes(path); // error here
any idea to what the problem is?
edited the code to this
string path = Path.Combine(folder, filename);
fileByte = File.ReadAllBytes(path);
the path is "F:\Web\Opgaver\Skirmer\Hjemmesiden\BETA\Skirmer 17-04-2012\Skirmer 17-04-2012\Billeder\Galleri\F:\Web\Opgaver\Skirmer\Hjemmesiden\BETA\Skirmer 17-04-2012\Skirmer 17-04-2012\Billeder\Galleri\2011\Vingsted\DSC_0001.JPG"
Error still happens. What I see is that ReadAllBytes requeres a string that shows the path, that I got, but it still shows error
You should not use / in the path, as the slash is an invalid character in Windows. Use Path.Combine to create it instead:
string path = Path.Combine(folder, filename);
I think that you want to use a backslash, or rather the property Path.DirectorySeparatorChar that returns the correct separator regardless of the file system:
string path = folder + Path.DirectorySeparatorChar.ToString() + filename;
Or you can use the Path.Combine method:
string path = Path.Combine(folder, filename);
What is the exact value of path variable?
Additionally, you should use Path.Combine to concatenate path parts into a full path.
As the documentation for File.ReadAllBytes states:
NotSupportedException - path is in an invalid format.
Your path is not in the correct format:
NotSupportedException path is in an invalid format.
MSDN: system.io.file.readallbytes
If the path you posted in your edited question really is the path you are trying read from then the reason you are getting the exception is because you have two colons in the path. The drive letter is repeated twice (F:\...F:\...).
The reason you end up with that path depends exactly on the contents of folder and filename in your call to Path.Combine(). It is unlikely that both folder and filename both start with the full path since Path.Combine() will return filename as the combined path in that case. It is most likely that your folder variable already contains two copies of the base path, with two drive letters and hence two colons and therefore causing the NotSupportedExeption, before you call Path.Combine().

illegal character in path

I am trying to get to a file located in
C:\Program Files (x86)\test software\myapp\demo.exe
In VS debugger i see the path as:
"\"C:\\\Program Files (x86)\\\test software\\\myapp\\\demo.exe\""
when i print it out i see in console :
"C:\Program Files (x86)\test software\myapp\demo.exe"
but when i try something like
FileInfo fi = new FileInfo(PathMentionedAbove);
i get Illegal character in path.
What is wrong? the file exists and path is correct. what's illegal above this path?
any help would be appreciated.
Your path includes " at the beginning and at the end. Drop the quotes, and it'll be ok.
The \" at the beginning and end of what you see in VS Debugger is what tells us that the quotes are literally in the string.
Try this:
string path = #"C:\Program Files (x86)\test software\myapp\demo.exe";
You seem to have the quote marks (") embedded in your string at the start and the end. These are not needed and are illegal characters in a path. How are you initializing the string with the path?
This can be seen from the debugger visualizer, as the string starts with "\" and ends with \"", it shows that the quotes are part of the string, when they shouldn't be.
You can do two thing - a regular escaped string (using \) or a verbatim string literal (that starts with a #):
string str = "C:\\Program Files (x86)\\test software\\myapp\\demo.exe";
Or:
string verbatim = #"C:\Program Files (x86)\test software\myapp\demo.exe";
The string is surrounded by double quotes. Yes, that's not a valid character in a path.
You should probably tackle it at the source, but you can strip them out with:
path = path.Replace("\"", "");
I usualy would enter the path like this ....
FileInfo fi = new FileInfo(#"C:\Program Files (x86)\test software\myapp\demo.exe");
Did you register the # at the beginning of the string? ;-)
try
"C:/Program Files (x86)/test software/myapp/demo.exe"

Categories