C# Save file with "/" in name - c#

FileName contains e.g. Legend/Dery//Times
File.WriteAllBytes("/Pictures" + FileName, buffer);
I can´t save the file because the "/" considered as path, I also can´t remove the "/", because I need it for further processing. Is there any way of saving such file?

You're out of luck. A forward slash can't be part of a file name.
You need to escape it somehow (i.e. change the name but provide a way of changing it back), but there isn't really a conventional way of doing that.
I've seen % been used for this purpose, with %% used to denote a single %, and something like %f for a forward slash, %b for a backslash, etc.

There are rules for names and folders defined by Microsoft that mean you are not allowed to do this.

Instead of escaping in i suggest normalizing your input both when you save a file and when you try to access a file:
//replace all illegal characters with regex (with a dash):
new Regex(#"[<>:""/\\|?*]").Replace("Inpu|t","-")
//Or just replace all non alpha numeric characters (with a dash):
new Regex(#"[^a-zA-Z0-9\-]").Replace("Inpu|t","-")
this way you will always have clean file and folder names and don't have to worry about illegal names.

Related

C# automatically substitutes forward-slash with back-slash in path...why?

I have a textbox where I put the name of a file that contains the forward-slash character '/'
When I grab the text from the textbox the '/' is automatically replaced with '\' and it obviously can't find the file, for example:
I write C:\Users\Temp\my/file.txt
I get C:\Users\Temp\my\file.txt
So, instead of opening "my/file.txt", it searches for a directory "my" which contains "file.txt"
How can I solve this?
If you're using Windows (which I assume you are, given the paths in your example), then / is an invalid character for a filename:
The easiest solution here would be to remove the slash from the filename as this is likely to cause further issues down the line.

Using The # symbol for a Directory so two backslashes aren't needed

this seems very simple but upon research I cannot find out how to use the # sign in a directory to prevent it from having to be to backslashes.
An example is of
DirectoryInfo folderInfo = new DirectoryInfo(#"C:\");
But In my Application The directory will be dynamic so I cannot do this:
DirectoryInfo folderInfo = new DirectoryInfo(#Globals.directoryRoute);
So I was wondering what is the correct way to put the # symbol before the string.
Globals.directoryRoute is set as C:\ but the user can change this input so I was hoping instead of having to parse out every double backslash I can use this to make it so only one backslash is needed.
Would this be an effective way of doing it or should I just parse out every second backslash?
The # prefix is a tool to tell the compiler to not take the backslash as an escape character within the following string. If the string is entered at runtime, you don't need to worry about that. So you can just use the content of Globals.directoryRoute as it is.
The double backslashes are only needed for string literals in your code. In memory, only a single backslash is stored in the string, so no # symbol is needed when dealing with strings that are already in memory. Similarly, user input does not need the double backslashes, since it is not interpreted in the same manner as source code. For instance, if you have a text box called txtPath, the user can simply type C:\some\path, not C:\\some\\path as you would normally need to do in source code. When you read the value of that text box in code, you can just use:
string path = txtPath.Text;
This will be the same as if you had the following code:
string path = #"C:\some\path";
or, equivalently:
string path = "C:\\some\\path";

Escaping directory chars in C#

I need to escape chars in a string I have, which content is C:\\blablabla\blabla\\bla\\SQL.exe to C:\blablabla\blabla\bla\SQL.exe so I could throw a process based on this SQL.exe file.
I tried with Mystring.Replace("\\", #"\"); and Mystring.Replace(#"\\", #"\"); but none worked.
How could I do this?
EDITED: Corrected type in string.
I very strongly suspect that you are looking this input string in the Visual Studio debugger and fooling yourself that there are actually 2 \ whereas in reality there aren't. That's the reason why attempting to replace \\ with \ doesn't do anything because in the original string there is no occurrence of \\. And since you are looking the output once again in the debugger, you are once again fooling yourself that there are 2 \.
Visual Studio debugger has this tendency to escape strings. Log it to a file or print to the console and you will see that there is a single \ in your input string and you don't need to replace anything.
It looks like you're trying to replace double backslash (#"\\") in a string with single backslash (#"\"). If so try the following
Mystring = Mystring.Replace(#"\\", #"\");
Note: Are you sure that the string even contains double backslashes? Certain environments will print out a single backslash as a double (debugger for example). Your comment mentioned my approach didn't work. That's a flag that there's not actually a double backslash in your string (else it would work).
The # character specifies a string as a verbatim literal string, but that is when constructing a string. If you use Mystring.Replace("\\", #"\") then nothing will be replaced, essentially, as the two strings are the same.
If you want a string without the escape characters, then either define it with:
string path = #"C:\Some\Directory\And\File.txt";
Or you can replace the \\ with / like so:
path = path.Replace('\\', '/');
It is worth noting, as mentioned by Darin Dimitrov, that the string containing two \ characters is likely just the display of the string (i.e. when using the debugger) and not the actual value of the string.
i think OP is asking how to escape \\ in File Path, if that in the case, as OP is not mentioning where he's trying to use this. so i'm putting a guess.
Then You use Path.Combine() method to get the FileName path.
Path.Combine() Documentation
where are you looking at this output? because it could be the string is what you expect, but viewing the value through the debugger, output window, etc. is escaping the slash
Use something like:
myStr = myStr.Replace(#"\\", #"\");
Make sure you assign the result of Replace method to myStr. Otherwise it goes into void ;)
Try adding "|DataDirectory|\MyFile.xyz" where you need it. It works with connection strings it might work with something else (I haven't really tried to apply it to something else).
I didn't understand what you want, if you just want do get the file name (escape directory chars) you can try:
string fileName = Path.GetFileName(YourString)
Noloman.... when you concatenate are you perhaps missing a "\" when concatenating the directory.. I am assuming that you are trying to join directory + some sub directory.. #noloman keep in mind that in C# "c:\Temp" is written like this "c:\Temp" or #"c:\Temp" one is Literal the other is how to represent a "\" in the legacy way of coding because the "\" is an escape Char and when dealing with directorys we represent all paths and sub paths with "\"
so perhaps by you replacing the "\" you are truly messing up your own expected process
Mystring = Mystring.Replace(#"\\", #"\");
should work for you unless you are truly meaning to do
Mystring = Mystring.Replace(#"\", "\"); which if you believe that you are expecting a "\" to be used to build the directory.. then of course it will not work.. because you have just in essense replaced the backslash with a return char.. I hope that this makes sense to you..
System.IO.Directory.GetCurrentDirectory(); you are using is also an Issue.. SQL Server is not that application thats running the code.. it's your .NET application so you need to either put the location of the SQL Server into a variable, app.config, web.config ect... please edit your question and paste the code that you are using to do what it is that you want to do inregards to the SQL Server Code.. you would probably want to look at the Are you wanting to do something like Process.Start(....) meaning the file name..?

Avoiding NotSupportedException using CreateDirectory in c#

I'm trying to recursively create a bunch of directories and certain directory names have ':' characters in which throws the above exception. I was hoping there may be a way to avoid this?
Below is a snip of the code I'm using:
foreach (TagLib.File tagFile in tagFiles)
{
GetInfo(tagFile, targetDir);
if (!Directory.Exists(TargetFullPath))
{
Directory.CreateDirectory(TargetFullPath);
System.IO.File.Copy(FilePath, TargetFullPath + "\\" + tagFile.Tag.Title + TargetExt);
} ...
Where 'TargetFullPath' = "G:\Users\Jon\Desktop\musictest\Journey\Journey: Greatest Hits"
Many Thanks :)
Colons are one of those characters you just can't use, but you could replace it easily enough. To also make sure you only replace characters in the file name portion (so you don't wipe out the backslashes making up the rest of the file path), you could use:
Path.Combine(Path.GetDirectoryName(TargetFullPath),Path.GetFileName(TargetFullPath).Replace(":","_"));
Assuming there could be other illegal characters in the file name (see this list), you'll want something more robust like a Regex statement.

C# Special Characters in String Crashing Program

I have a slight problem with a path:
"D:\\Music\\DJ Ti%C3%ABsto\\Tiesto\\Adagio For Strings (Spirit of London).mp3"
"D:\\Music\\Dj Tiësto\\Tiesto\\Adagio For Strings (Spirit of London).mp3"
Currently, when it sends that path to my Audio Library, it cannot open the path. (the reason for it crashing is trying to assign a -1 to a trackbar...but it's irrelevant).
So I'm wondering, is there anyway to prevent C# from switching special characters with %[code]? I've done a .Replace for "[" and "]", but I rather not have to look up every single special character, and add a line of code to prevent it. Is there anyway around this?
Call Uri.UnescapeDataString.
By the way, when putting paths in strings, you can put an # sign before the string to tell the compiler not to process escape codes, like this: #"D:\Music\DJ Tiësto\Tiesto\Adagio For Strings (Spirit of London).mp3". This way, you don't need to double up every backslash.

Categories