I have :
string Combine = Path.Combine("shree\\", "file1.txt");
string Combine1 = Path.Combine("shree", "file1.txt");
Both gives same result :
shree\file1.txt
What actually happen behind Path.Combine?Which is the best coding practice to do this.please clear my vision.Thanks.
If the first path (shree or shree\\) does not end with a valid separator character (e.g. DirectorySeparatorChar) it is appended to the path before concatenation.
So
string path1 = "shree";
string path2 = "file1.txt";
string combined = Path.Combine(path1, path2);
will result in "shree\file1.txt", while
string path1 = "shree\\";
already contains a valid separator character, so the Combine method will not add another one.
Here you typed two slashes in the string variable (path1). The first one just acts as an escape character for the second one. This is the same as using a verbatim string literal.
string path1 = #"shree\";
More information on the Combine method can be found on MSDN:
http://msdn.microsoft.com/en-us/library/fyy7a5kt.aspx
Use the second one. This way you don't care about what is the directory separator.
What actually happen behind Path.Combine?
It builds you a path... so it's doesn't matter what of those two you will use. but those \\ are redundant.
If you're interested with micro optimization, create a test which of the two is faster.
Related
I'm trying to compare below two strings using c# asp.net core. The motivation is to compare two paths except path parameter (without manually splitting and comparing one by one). Is it possible to do this in single line using any in-build method?
Requested: /api/v1/schedules/S210715001/comments
Original: /api/v1/schedules/{id}/comments
Thanks in advance.
You could create a regex pattern of the original string containing curly brackets and then match against the requested string.
string original = #"/api/v1/schedules/{id}/comments";
string requested = #"/api/v1/schedules/S210715001/comments";
string originalPattern = Regex.Replace(original, #"\{[^\}]*\}", #"\w*");
var isMatch = Regex.Match(requested, $"^{originalPattern}$", RegexOptions.IgnoreCase).Success;
There is a built-in fuction called Path.GetFileName in System.IO allowing you to extract a file name from a whole path.
Here is how to use it:
var original = "/api/v1/schedules/S210715001/comments";
var requested = "api/v1/schedules/{id}/comments";
Console.WriteLine("original: " + Path.GetFileName(original));
Console.WriteLine("requested: " + Path.GetFileName(requested));
output:
original: comments
requested: comments
Note : there are some subtilities on what is considered a directory separator : backslash, forward slash etc. (see here), but I think it's easier to use than regular expressions.
I have a sub that is supposed to play a music file.
I can locate MyDocuments easily.
I can even use Path.Combine to concatenate the rest of the string.
The full path should look something like this:
......Documents\JukeBox\MichaelJackson\01.wav
But I am getting double slashes not single ones
private static void playChoice(string band, int choice)
{
var myDocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string filename = "0" + choice;
string[] paths = { myDocs, "JukeBox", band, filename, ".wav" };
var fullPath = Path.Combine(#paths);
var player = new System.Media.SoundPlayer(fullPath);
player.Play();
}
A) How do I strip out the double slashes since my verbatim specifier does not work
B) The code looks awful - is there a better approach - or does anyone have a link to helpful literature
Verbatim string literals is a feature of string literals that affect how the literal is parsed.
You don't have any string literals; that is completely irrelevant.
#paths is a completely different feature that lets an identifier be named after a keyword (eg, int #int). It's also irrelevant.
You're probably seeing the value in the debugger, which displays the C# source to write the value, including escape sequences. Your string doesn't actually have double-slashes.
However, Path.Combine() combines folders (by adding slashes between them); it makes no sense to pass an extension there.
In order to be able to read a file in asp.net, the file path must be written in this:
1.
C:\\yung\\Desktop
returns
however, the string that the fileUpload get returns is
2.
C:\yung\Desktop
After reading the comments i have this code:
string FilePath = FileUploadPublicInfo.PostedFile.FileName;
System.IO.StreamReader file = new System.IO.StreamReader(FilePath);
string line = File.ReadLines(FilePath.ToString()).Skip(4).ToString();
TextBox1.Text = line.ToString();
But now its giving this error:
System.Linq.Enumerable+<SkipIterator>d__30`1[System.String]
How to solve this problem?
Thank you.
I'm not so sure I understand the question, but I think you are looking for string.Replace:
string DoubleSlash(string singleSlash)
{
return singleSlash.Replace(#"\", #"\\");
}
The reason backslashes disappear is that C# compiler treats slashes in string literals as a special "escape" character. Because of this treatment, backslash needs to be encoded as two slashes in a regular string literal.
C# offers two ways of inserting backslashes the way you need:
Use verbatim literals - prefix it with "at" sign, i.e. #"C:\\yung\\Desktop", or
Double each slash - put two slashes for each slash in the result: C:\\\\yung\\\\Desktop
Ok, i have manage to solve this problem, turns out it was not reading anything.
This is the code that i finally get:
This is to retrieve the File's path, using this, would give the file path will double slash, so there is not a need for Replace(#"\",#"\")
string FilePath = FileUploadPublicInfo.PostedFile.FileName;
Then read the specified file
System.IO.StreamReader file = new System.IO.StreamReader(FilePath);
If you know which line you specifically want, this retrieves the 5th line
string line = File.ReadLines(FilePath.ToString()).Skip(4).First().ToString();
Thank you so much for your help...
If I do this:
string path = "\\myServer\myFile.txt"
I get a compilation error. So I do this:
string path = #"\\myServer\myFile.txt"
Altought the output of path in QUICK WATCH of Visual Studio is:
\\\\myServer\myFile.txt
Is there any clean way to avoid the problem of this 4 backslashes?
Although the output of path is:
\\\\myServer\myFile.txt
No, it's not. The value you might see in the debugger would be
\\\\myServer\\myFile.txt
which is just the debugger escaping the value for you.
The value of the string has a double backslash at the start, and a single backslash in the middle. For example:
Console.WriteLine(#"\\myServer\myFile.txt");
will print
\\myServer\myFile.txt
It's important to differentiate the actual content of the string, and some format seen in the debugger.
If you want to express the same string in code without using a verbatim string literal (that's the form starting with #) you can just escape each backslash:
string path = "\\\\myServer\\myFile.txt";
Again, the actual value there only has a total of three backslashes. For example:
string path1 = "\\\\myServer\\myFile.txt";
string path2 = #"\\myServer\myFile.txt";
Console.WriteLine(path1 == path2); // true
They're different literals representing the same string content.
string path = #"\\" will not create a string with 4 backslashes. It might look like that in the debugger, but try to Debug.WriteLine() it: there's only 2.
No, you have the choise between
string test = #"\\myServer\myFile.txt";
or
string test = "\\\\myServer\\myFile.txt";
Both contains \\myServer\myFile.txt
In C#, I have a filename that needs to converted to be double-escaped (because I feed this string into a regex).
In other words, if I have:
FileInfo file = new FileInfo(#"c:\windows\foo.txt");
string fileName = file.FullName;
fileName is: c:\\\\windows\\\\foo.txt
But I need to convert this to have sequences of two literal backslashes \\ in the fileName.
fileName needs to be #"c:\\\\windows\\\\foo.txt", or "c:\\\\\\\\windows\\\\\\\\foo.txt".
Is there an easy way to make this conversion?
I Think you're looking for Regex.Escape
Regex.Escape(#"c:\test.txt") == #"C:\\Test\.txt"
notice how it also escapes '.'
simplest without resorting to regex for this part:
string fileName = file.FullName.Replace(#"\", #"\\\\");
based on OP, but I think you really want this:
string fileName = file.FullName.Replace(#"\", #"\\");
That being said, I can't see how you want to use it... it shouldn't need escaping at all... maybe you should post more code?