In my Application there is a class that works with PdfSharp to generate some PDF reports. I specified output folder as a string with verbatim
string file_path = #"D:\Intranet\Students\DailyMarks\";
Also there is a StringBuilder that generates file name based on some ID and DateTime:
... sb.Append(document.Type); sb.Append(document.Id); sb.Append(DateTime.Now.ToShortString());
And finally I do the following
file_path + sb.toString();
But my Application cathes an exception. After debugging session I see that actually my file_path is
file_path = "D:\\Intranet\\Students\\DailyMarks\\...";
As I understand it happens after concatenation of origin file with StringBuilder's toString() call.
I tried to replace file_path string with something like this:
file_path = file_path.Replace(#"\\",#"\");
but it doesn't work. Where did I do wrong?
Probably this is caused by the DateTime.Now.ToShortString() method, which adds forbidden characters to the path (:).
It's totally fine.
"D:\\Intranet\\Students\\DailyMarks\\..." == #"D:\Intranet\Students\DailyMarks\..."
In regular string you need to escape slashes, in verbatim it's done automatically
Another similar situation I faced today was about sending Japanese 「:」 (colon with whole inside) as a file's name's element and it worked. I wonder, why Russian colon calls an exception and Japanese not. Very interesting.
Related
I'm completely a junior here. I have tried something like
save a path and file string in a file like:
c:\aaa\bbb\text.txt
then I need to read again as path but I get c:\aaa\bbb\text.txt from streamreader, but I need c:\\\aaa\\\bbb\\\text.txt
Can anyone help me?
I think you might be confusing string literals with a string.
Say I write var myString = "\\" or var myString = #"\", this will show in the debugger as \\, because the debugger will format it as a literal. But if print it to the console, a file, or press the magnifying glass next to the string in the debugger, it will be shown as \, because that is the actual string value. See also verbatim string literal
So, if you do myStreamWriter.Write("c:\\aaa\\bbb\\text.txt");, you will be actually saving the string c:\aaa\bbb\text.txt, and that is also the string that will be read back.
However I fail to understand why you would want three slashes, I can only assume the OP thinks the escaping is done multiple times.
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 need to send the value I receive from the model with this link, the proposalName field must be in quotes.How can I do it?
Here is my service url.
string path = string.Format("{ProposalId:{proposalId},ProposalName:{"proposalName"},VendorId:{vendorId}}",
Uri.EscapeDataString(proposalId.ToString()),
Uri.EscapeDataString(proposalName),
Uri.EscapeDataString(vendorId.ToString()));
You can simply put quotes around by escaping the quotes, like this -
string path = string.Format("{{0},ProposalName:\"{1}\",VendorId:{2}}",
Uri.EscapeDataString(proposalId.ToString()),
Uri.EscapeDataString(proposalName),
Uri.EscapeDataString(vendorId.ToString()));
As per your updated question, if you need to pass double quotes in URL, you need to encode it to %22
You can also use URI which allows a lot of flexibility with urls. For example -
Uri myUri = new Uri("http://google.com/search?hl=en&q=\"query with quotes\"");
Going with your example - Replace EscapeDataString with Uri.EscapeUriString. It will escape the chracter to form a valid URL. " will get replaced by %22
Some suggestions here and here-
Your problem exactlly in the {"1"} part. The double quotation mark " should be outside the {}, not inside them.
here is the fixed code.
string path = string.Format("{{0},ProposalName:\"{1}\",VendorId:{2}}",
Uri.EscapeDataString(proposalId.ToString()),
Uri.EscapeDataString(proposalName),
Uri.EscapeDataString(vendorId.ToString()));
or
string path = string.Format(#"{{0},ProposalName:""{1}"",VendorId:{2}}",
Uri.EscapeDataString(proposalId.ToString()),
Uri.EscapeDataString(proposalName),
Uri.EscapeDataString(vendorId.ToString()));
and if you are using C# 6 then you can write it as following
string path = $"{Uri.EscapeDataString(proposalId.ToString())},ProposalName:\"{Uri.EscapeDataString(proposalName)}\",VendorId:{Uri.EscapeDataString(vendorId.ToString())}";
This might do the trick for you
\"{1}\"
instead of
{"1"}
because you can put \ symbol to indicate escape sequence followed by a reserved characters
So
string.Format("{{{0},ProposalName:\"{1}\",VendorId:{2}}}",
I think escaping the quotes and placing them outside the brackets will work:
"{{0},ProposalName:\"{1}\",VendorId:{2}}"
Depending on the C# version, you can also do it like this, which I often think is an easier and cleaner way to do it:
string path = $"{proposalId},ProposalName:\"{proposalName}\",VendorId:{vendorId}";
You have two problems:
Wrong quotation (should be outside the braces {...} and escaped)
Incorrect { and } escape: {{ means just a single '{' in a formatting string
Should be
string path = string.Format("{{{0},ProposalName:\"{1}\",VendorId:{2}}}",
please, notice
escaped quotations \" which are outside {1}
tripled curly braces{{{ and }}}
Edit: in your edited question you have the same errors:
string format =
"http://mobile.teklifdosyam.com/VendorReport/GetListProposalService?&page=1&start=0&limit=10&filter=" +
"{{ProposalId:{0},ProposalName:\"{1}\",VendorId:{2}}}";
string path = string.Format(format,
Uri.EscapeDataString(proposalId.ToString()),
Uri.EscapeDataString(proposalName),
Uri.EscapeDataString(vendorId.ToString()));
please, notice escaped quotations \" which are outside the {1}, double '{{' and tripled '}}}'. When formatting you have to use numbers as place holders: so {"proposalName"} must be changed into {0}
I'm trying to format a String using the String.Format function, but my double quotes keep getting replaced by the HTML safe version of this (").
Needless to say this is not the result I would expect.
My current code looks like this
string String= String.Format("{0}: {{ name: \"{1}\"}}", node.Category, node.Name);
// Output ==> SomeCategory: { name: "SomeName" }
I've tried replacing the " by actual quotes in the output, but that also didn't work.Is there some voodoo I can use to fix this?
Thanks in advance!
This is not caused by String.Format(), more likely it is caused by whatever you use to view the data, or by something that happens before you view the data.
Judging from your format string it looks like you're trying to create a JSON string to return (possibly from a service). There is a big chance something will HTML encode your string on it's way to the client. The problem lays there, not in your string formatting, and thus trying to fix it there will not work.
Try to use HTML decode and encode
That way you can turn them in actual quotes.
HttpUtility.HtmlDecode
Source: http://msdn.microsoft.com/en-us/library/aa332854%28v=vs.71%29.aspx
Stackoverflow source: " instead sign of quote (")
My web program is getting an error when trying to access a file in a code behind C# program that has a backward slash between the directory name and the file name. The address for the file comes into my web page with a query value of 'deaths\bakerd.htm'. The browser, however, converts it to 'deaths%08akerd.htm'.
The url in the webpage reads
'http://localhost:57602/obitm.aspx?url=deaths%08akerd.htm'
and says the web page cannot be found but the webpage obitm.aspx does exist so why would it say it doesn't?
If I manually change the value of the query value in Windows Explorer to 'deaths/bakerd.htm' it doesn't do any conversion when coming in as a query value in the browser and I am able to access the file in my C# program.
I tried to change the query value in javascript using
thisurl = url.replace("\\", "/")
but that didn't change anything.
I haven't tried any conversion in my C# program. So how do I programmatically change the '\' to a '/'? I have no idea why this is happening and is very confusing. Any help is appreciated.
Just Converting \ to / in the URL string won't work for you, because in this case the "\b" is being turned into the backspace character which gets encoded into %08 - which is the HEX value for the ASCII equivalent of the backspace character.
To fix this one occurrence, you could convert the "%08" into the string "/B" but there are lots of HTML codes for the various characters that it would not be productive or fun for you to try.
Where are you getting the original string containing the file name name from?
If it is something that you have control over then convert the "\" to "/" at the point when you read the path / name of the file and before you pass it in a URL to the Web App.
you could also HTMLEncode the path before sending it so that the string becomes
http://localhost:57602/obitm.aspx?url=deaths%92Bakerd.htm'
Try using verbatim string by prefixing with # symbol
string url = #"http://localhost:57602/obitm.aspx?url=deaths\bakerd.htm".Replace("\\","/").ToString();
try thisurl = url.Replace("\\", "/");
Just like in javascript.
To parse query string parameter, you can user:
NameValueCollection qscoll = HttpUtility.ParseQueryString(querystring);
Here us MSDN help
or you can:
HttpUtility.UrlEncode(Request.QueryString["url"]);