Using System.IO, I tried the following code:
string[] files = Directory.GetFiles("\\folder\\folder_2\\folder_3");
And got the following exception:
"System.IO.DirectoryNotFoundException - It was not possible to locate part of the path 'C:\folder\folder_2\folder_3)' "
I don't know why "c:\" was added to the original string, and I can't seem to keep the method from doing so. What am I doing wrong?
Any help is much appreciated.
A backslash (\) at the start of a path makes it an absolute path. Remove the first \ if you want a relative path:
string[] files = Directory.GetFiles("folder\\folder_2\\folder_3");
You need to escape each of the beginning backslashes in your path, you only escaped a single slash. Use either correct escaping:
string[] files = Directory.GetFiles("\\\\folder\\folder_2\\folder_3");
Or you can use a verbatim string literal:
string[] files = Directory.GetFiles(#"\\folder\folder_2\folder_3");
Full explanation found in MSDN Documentation
In addition to the answers provided, you could use verbatim string literals, which will pass the string exactly without the need for escaping with all the messy backslashes.
In your case this would be
string[] files = Directory.GetFiles(#"folder\folder_2\folder_3");
Notice that the # is outside of quotes, but stuck to the opening quotes, this tells C# to use it, (pardon the pun) literally. The syntax highlighting for this kind of string will also change in Visual Studio, just FYI.
edit: saw a comment by another user advising you to use the #, it's the same thing. Sorry did not see this earlier.
Read about them here at MSDN
Related
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...
I'm having a doubt about this
I tried to save a xmlDocument in a network device folder, not mapping.
Where:
config.plc.Path ="\\IpAdress\\folder\\";
doc.Save(config.plc.Path + "file.xml");
It was throwing an exception, and I just fixed it using the '#'
doc.Save(#config.plc.Path + "file.xml");
When I add the parameter as verbatim string with #, it gets like this:
config.plc.Path ="\\\\IpAdress\\\\folder\\\\";
is the first time I see a path like this, with
\\\\
can someone help me to understand this?
It's simple, \\ is just an escape sequence for \. # (Verbatim String) has to be used to avoid this
I created a directory inside my WPF solution called Sounds and it holds sound files.(For example: mySound.wav).
Inside my code I use a List and there I have to add to those strings that relate to the sound files. In the beginning I used #"C:..." but I want it to be something like "UNIVERSAL" path. I tried using: "\Sounds\mySound.wav" but it generates an error.
The lines that I use there this directory are:
myList.Add("\Sounds\11000_0.2s.wav");//Error
using (WaveFileReader reader = new WaveFileReader(sourceFile))
where sourceFile is a string which express a path of the file.
Make sure that you check CopyToOutputDir in the properties of the soundfile, that will make sure the file is copied to the location you program runs from.
Also don't use single backslashes in the path since its an escape character.
Instead, do one of the following things:
Use a verbatim string:
#"Sounds\11000_0.2s.wav"
Escape the escape char:
"Sounds\\11000_0.2s.wav"
Use forward slashes:
"Sounds/11000_0.2s.wav"
For more information on string literals check msdn.
You either need to escape the / in the string or add the string literal indicator # at the beginning of the string.
Escape example:
var myFilePath = "c:\\Temp\\MyFile.txt";
String literal example:
var myFilePath = #"c:\Temp\MyFile.txt";
I've got a .NET 3.5 web application written in C# doing some URL rewriting that includes a file path, and I'm running into a problem. When I call string.Split('/') it matches both '/' and '\' characters. Is that... supposed to happen? I assumed that it would notice that the ASCII values were different and skip it, but it appears that I'm wrong.
// url = 'someserver.com/user/token/files\subdir\file.jpg
string[] buffer = url.Split('/');
The above code gives a string[] with 6 elements in it... which seems counter intuitive. Is there a way to force Split() to match ONLY the forward slash? Right now I'm lucky, since the offending slashes are at the end of the URL, I can just concatenate the rest of the elements in the string[], but it's a lot of work for what we're doing, and not a great solution to the underlying problem.
Anyone run into this before? Have a simple answer? I appreciate it!
More Code:
url = HttpContext.Current.Request.Path.Replace("http://", "");
string[] buffer = url.Split('/');
Turns out, Request.Path and Request.RawUrl are both changing my slashes, which is ridiculous. So, time to research that a bit more and figure out how to get the URL from a function that doesn't break my formatting. Thanks everyone for playing along with my insanity, sorry it was a misleading question!
When I try the following:
string url = #"someserver.com/user/token/files\subdir\file.jpg";
string[] buffer = url.Split('/');
Console.WriteLine(buffer.Length);
... I get 4. Post more code.
Something else is happening, paste more code.
string str = "a\\b/c\\d";
string[] ts = str.Split('/');
foreach (string t in ts)
{
Console.WriteLine(t);
}
outputs
a\b
c\d
just like it should.
My guess is that you are converting / into \ somewhere.
You could use regex to convert all \ slashes to a temp char, split on /, then regex the temp chars back to \. Pain in the butt, but one option.
I suspect (without seeing your whole application) that the problem lies in the semantics of path delimiters in URLs. It sounds like you are trying to attach a semantic value to backslashes within your application that is contrary to the way HTTP protocols define and use backslashes.
This is just a guess, of course.
The best way to solve this problem might be modifying the application to encode the path in some other way (such as "%5C" for backslashes, maybe?).
those two functions are probably converting \ to / because \ is not a valid character in a URL (see Which characters make a URL invalid?). The browser (NOT C#, as you are inferring) is assuming that when you are using that invalid character, you mean /, so it is "fixing" it for you. If you want \ in your URL, you need to encode it first.
The browsers themselves are actually the ones that make that change in the request, even if it is behind the scenes. To verify this, just turn on fiddler and look at the URLs that are actually getting sent when you go to a URL like this. IE and Chrome actually change the \ to / in the URL field on the browser itself, FireFox doesn't, but the request goes through that way anyways.
Update:
How about this:
Regex.Split(url, "/");
A string variable str contains the following somewhere inside it: se\">
I'm trying to find the beginning of it using:
str.IndexOf("se\\\">")
which returns -1
Why isn't it finding the substring?
Note: due to editing the snippet showed 5x \ for a while, the original had 3 in a row.
Your code is in fact searching for 'se\\">'. When searching for strings including backslashes I usually find it easier to use verbatim strings:
str.IndexOf(#"se\"">")
In this case you also have a quote in the search string, so there is still some escaping, but I personally find it easier to read.
Update: my answer was based on the edit that introduced extra slashes in the parameter to the IndexOf call. Based on current version, I would place my bet on str simply not containing the expected character sequence.
Update 2:
Based on the comments on this answer, it seems to be some confusion regarding the role of the '\' character in the strings. When you inspect a string in the Visual Studio debugger, it will be displayed with escaping characters.
So, if you have a text box and type 'c:\' in it, inspecting the Text property in the debugger will show 'c:\\'. An extra backslash is added for escaping purposes. The actual string content is still 'c:\' (which can be verified by checking the Length property of the string; it will be 3, not 4).
If we take the following string (taken from the comment below)
" '<em
class=\"correct_response\">a
night light</em><br
/><br /><table
width=\"100%\"><tr><td
class=\"right\">Ingrid</td></tr></table>')"
...the \" sequences are simply escaped quotation marks; the backslashes are not part of the string content. So, you are in fact looking for 'se">', not 'se\">'. Either of these will work:
str.IndexOf(#"se"">"); // verbatim string; escape quotation mark by doubling it
str.IndexOf("se\">"); // regular string; escape quotation mark using backslash
This works:
string str = "<case\\\">";
int i = str.IndexOf("se\\\">"); // i = 3
Maybe you're not correctly escaping one of the two strings?
EDIT there's an extra couple of \ in the string you are searching for.
Maybe the str variable does not actually contain the backslash.
It may be just that when you mouse over the variable while debugging, the debugger tooltip will show the escape character.
e.g. If you put a breakpoint after this assignment
string str = "123\"456";
the tooltip will show 123\"456 and not 123"456.
However if you click on the visualize icon, you will get the correct string 123"456
Following code:
public static void RunSnippet()
{
string s = File.ReadAllText (#"D:\txt.txt");
Console.WriteLine (s);
int i = s.IndexOf("se\\\">");
Console.WriteLine (i);
}
Gives following output:
some text before se\"> some text after
17
Seems like working to me...
TextBox2.Text = TextBox1.Text.IndexOf("se\"">")
seems to work in VB.
DoubleQuotes within a string need to be specified like "" Also consider using verbatim strings - So an example would be
var source = #"abdefghise\"">jklmon";
Console.WriteLine(source.IndexOf(#"se\"">")); // returns 8
If you are looking for se\">
then
str.IndexOf(#"se\"">")
is less error-prone. Note the double "" and single \
Edit, after the comment: it seems like the string may contain ecaping itself, in which case in se\"> the \" was an escaped quote, so the literal text is simply se"> and the string to use is Indexof("se\">")