File.delete not working for 'directorya\directoryb' - c#

I want to create some function which export report to excel file,
but when I try to delete temp data it's not working.
File.Delete(tempFileName);
I try to messagebox 'tempFileName' it's correct
D:\test\bin\Debug\temptemp1.xls
then I try to test manually delete it
File.Delete("D:\test\bin\Debug\temptemp1.xls");
it's give error result 'unrecognized escape sequence';
I try to change it like this
File.Delete("D:/test/bin/Debug/temptemp1.xls");
and it's work smoothly
I see documentation File.Delete here
and it's using '\' not '/';
can anyone explain this to me?
(I use vs 2010 and .net 4 winform)

In a regular string constant, the \ character is an escape character so, if you want to include a literal backslash, you need to escape it (with itself):
File.Delete("D:\\test\\bin\\Debug\\temptemp1.xls");
Otherwise \t will become a tab, \b a backspace and \D give you your unrecognised escape sequence error.
Alternatively, you use a raw string to avoid all the complexities that come from escaping:
File.Delete(#"D:\test\bin\Debug\temptemp1.xls");
which doesn't do the escaping.
The reason that it works with the forward slash / is because Windows has, for a long time, been able to handle both styles (in the API, though not in the command interpreter cmd.exe).

Try..
File.Delete(#"D:\test\bin\Debug\temptemp1.xls");
OR...
File.Delete("D:\\test\\bin\Debug\\temptemp1.xls");
Backslash is a special character. As documented here...
http://msdn.microsoft.com/en-us/library/aa691090(v=vs.71).aspx
A character that follows a backslash character () in a
regular-string-literal-character must be one of the following
characters: ', ", \, 0, a, b, f, n, r, t, u, U, x, v. Otherwise, a
compile-time error occurs.

Related

Is there a possibility to write or print \ into a console

I have a question. Can I write \ into a conosle in vscode? I tried to print an ascii character into the console for my little project that I am working on, because I am trying to learn c#
I have tired everything and the only thing I get is this message: the constant contains the newline character.
I know what it means because \n make a new line. I tried to search the internet and I didnt see anything related to what I am asking. Any help?
Thank you for seeing this question
-Henry
The backslash (\) is used as an escape character in C#. You can find the documentation about escape sequences here
When you type just one backslash, the compiler will therefore interpret this character (and the next one) as an escape sequence.
Like Progman suggested, you can type "\\" to display a backslash in the Console.
Yes, you can print \ on console.
\ is actually an escape sequence, hence the confusion.
Check this for escape sequences : here
To print "\" on the console in C# -
Console.WriteLine("Print \\");

C# regex.escape unexpected behavior when processing "."

Hey I have an issue with Regex.Escape I'm trying to feed it an Email from TextBox Controll. The function recieves "test#test.test". What I expect to get is this "test#test\.test" Regex.Escape escapes the dot character. Hovever what I get instead is "test#test\\.test" which is very confusing. I plan on handing that string down to an SQL query and I'm worried abut users misbehaving.
holder.address = Regex.Escape(EmailAddressInput.Text);
This is how I assign resulting string to field in holder class.
I have been researching this problem on my own but most sources (including MSDN) suggest to prefix the dot ("the special character") with one backslash.
As it is right now backslash escapes backslash and result is a badly formatted email address.
var s = "test#test\\.test"; means the s holds the test#test\.test string. Your issue does not exist. There is a single backslash. Click the magnifier button on the right - you will see that in the Text Visualizer.
Regex has to have \\ because its escaping the \
the string itself actually only has one \ in it.

Add special characters to alphanumeric regex

Brand new to using Regular Expressions. I have one that currently accepts alphanumeric characters only. I need to add the following special characters to the regex:
# #$%*():;"',/? !+=-_
Here is the regular expression:
RegularExpression(#"^[a-zA-Z\s.,0-9-]{1,30}$",
When I try to add the special characters, I alter the Regex like so:
RegularExpression(#"^[a-zA-Z\s.,0-9-# #$%*():;"',/? !+=-_]{1,30}$"
However this throws an error starting with the ' character that says Newline in constant.
I've tied to escape both the " and the ' characters, however without any luck.
the problem comes from the double quote that need to be escaped (""), not from the single quote.
#"^[a-zA-Z\s.,0-9##$%*():;""'/?!+=_-]{1,30}$"
note that the - must be at the last (or first) position in a character class, since it has a special meaning (define ranges)
These regexs' are equivalent to yours.
Both use tilde ~ as the delimeter.
Both use double quotes on the regex strings.
Note that in order for the the dash - in class to be interpreted literally and not as a range operator, it must exist somewhere disambiguous, or be escaped.
A good place to put it is between valid ranges (or at the beginning or end of a class).
For example [a-z-0-9] is a good place.
Edit - '-' Literal may have to be escaped or beginning/end of class. (This case was for Perl/PCRE engines)
This one ^[a-z-A-Z0-9_\s.,##$%*():;"',/?!+=]{1,30}$ is your regex without duplicate chars.
To make it more readable noting that the word class is contained, it can be reduced to
^[\w-\s.,##$%*():;"',/?!+=]{1,30}$
Edit - Php test cases removed.

Why does .NET add an additional slash to the already existent slashes in a path?

I've noticed that C# adds additional slashes (\) to paths. Consider the path C:\Test. When I inspect the string with this path in the text visualiser, the actual string is C:\\Test.
Why is this? It confuses me, as sometimes I may want to split the path up (using string.Split()), but have to wonder which string to use (one or two slashes).
The \\ is used because the \ is an escape character and is need to represent the a single \.
So it is saying treat the first \ as an escape character and then the second \ is taken as the actual value. If not the next character after the first \ would be parsed as an escaped character.
Here is a list of available escape characters:
\' - single quote, needed for character literals
\" - double quote, needed for string literals
\\ - backslash
\0 – Null
\a - Alert
\b - Backspace
\f - Form feed
\n - New line
\r - Carriage return
\t - Horizontal tab
\v - Vertical quote
\u - Unicode escape sequence for character
\U - Unicode escape sequence for surrogate pairs.
\x - Unicode escape sequence similar to "\u" except with variable length.
EDIT: To answer your question regarding Split, it should be no issue. Use Split as you would normally. The \\ will be treated as only the one character of \.
.Net is not adding anything to your string here. What your seeing is an effect of how the debugger chooses to display strings. C# strings can be represented in 2 forms
Verbatim Strings: Prefixed with an # sign and removes the need o escape \\ characters
Normal Strings: Standard C style strings where \\ characters need to escape themselves
The debugger will display a string literal as a normal string vs. a verbatim string. It's just an issue of display though, it doesn't affect it's underlying value.
Debugger visualizers display strings in the form in which they would appear in C# code. Since \ is used to escape characters in non-verbatum C# strings, \\ is the correct escaped form.
Okay, so the answers above are not wholly correct. As such I am adding my findings for the next person who reads this post.
You cannot split a string using any of the chars in the table above if you are reading said string(s) from an external source.
i.e,
string[] splitStrings = File.ReadAllText([path]).Split((char)7);
will not split by those chars. However internally created strings work fine.
i.e.,
string[] splitStrings = "hello\agoodbye".Split((char)7);
This may not hold true for other methods of reading text from a file. I am unsure as I have not tested with other methods. With that in mind, it is probably best not to use those chars for delimiting strings!

Simple regex not working in c#

/news/article-title.html
is not being caught by the regex:
^/news/[^(archives)].+.html
?
I'm trying to have articles that do NOT have "archives" in the filename, but start with "/news/"
Thanks!
You should use a negative lookahead. Character classes only work for a single character. Also, don't forget to escape the dot.
If "archives" cannot be at the beginning:
^/news/(?!archives).+\.html
If "archives" cannot anywhere:
^/news/((?!archives).)+\.html
More tips:
Disallow archives as a whole word: (?!archives\b).+ or (?!archives-).+
make sure \.html is at the end (it may appear more than once): \.html(?=$|[?&])
You can't use the not of a character block to not an entire string.
[^(archives)]
This is interpreted as a character that is not one of the following: (, a, r, c, h, i, v, e, s or ).

Categories