Why Does .Net Add an Additional Slash to the Already Existent Slashes in a Path

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

.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.

Why does C# add extra backslashes to my data?

I think you can try this method

 var raw = new WebClient().DownloadString("http://ip-api.com/json");

var json = JToken.Parse(raw.ToString());

string Latitude = (string)json[@"lat"];
string Longitude = (string)json[@"lon"];

Difference between forward slash (/) and backslash (\) in file path

/ is the path separator on Unix and Unix-like systems. Modern Windows can generally use both \ and / interchangeably for filepaths, but Microsoft has advocated for the use of \ as the path separator for decades.

This is done for historical reasons that date as far back as the 1970s, predating Windows by over a decade. In the beginning, MS-DOS (the foundation to early Windows) didn't support directories. Unix had directory support using the / character since the beginning. However, when directories were added in MS-DOS 2.0, Microsoft and IBM were already using the / character for command switches, and because of DOS's lightweight parser (descended from QDOS, designed to run on lower end hardware), they couldn't find a feasible way to use the / character without breaking compatibility with their existing applications.

So, to avoid errors about "missing a switch" or "invalid switch" when passing filepaths as arguments to commands such as these:

cd/                        <---- no switch specified
dir folder1/folder2 <---- /folder2 is not a switch for dir

it was decided that the \ character would be used instead, so you could write those commands like this

cd\
dir folder1\folder2

without error.

Later, Microsoft and IBM collaborated on an operating system unrelated to DOS called OS/2. OS/2 had the ability to use both separators, probably to attract more Unix developers. When Microsoft and IBM parted ways in 1990, Microsoft took what code they had and created Windows NT, on which all modern versions of Windows are based, carrying this separator agnosticism with it.


As backward compatibility has been the name of the game for Microsoft from all of the major OS transitions that they've undertaken (DOS to Win16/DOS, to Win16/Win32, to Win32/WinNT), this peculiarity stuck, and it will probably exist for a while yet.

It's for this reason that this discrepancy exists. It should really have no effect on what you're doing because, like I said, the WinAPI can generally use them interchangeably. However, 3rd party applications will probably break if you pass a / when they expect a \ between directory names. If you're using Windows, stick with \. If you're using Unix or URIs (which have their foundation in Unix paths, but that's another story entirely), then use /.


In the context of C#: It should be noted, since this is technically a C# question, that if you want to write more "portable" C# code that works on both Unix and Windows (even if C# is predominantly a Windows language), you might want to use the Path.DirectorySeparatorChar field so your code uses the preferred separator on that system, and use Path.Combine() to append paths properly.

Reading a line from text file returns unwanted slash

The debug view for strings escapes things that would normally be escaped in code. This means that things like inline quotes or real \'s will be escaped with a \ (making quotes look like \" and single slashes look like \\).

These slashes are not in the actual string, they are only there in the text viewer. You can verify that by writing out the string to the console or the debug output. Your string.Replace didn't work because there was nothing to replace.

You can verify this with a very small console program:

private static void Main(string[] args)
{
string s = ((char)34) + "492200" + ((char)34) + "NNNNNNNNN";

Console.WriteLine(s);

Console.ReadKey(true);
}

Character 34 is the " character, so I constructed the string without using \'s to escape them in code. Setting a breakpoint at the ReadKey call and examining the variable s shows "\"492200\"NNNNNNNNN", but the console prints out the string without the \'s:

Missing Slashes

You'll also notice that the string has been surrounded by quotes as well that are not part of the original string. Clicking on the little magnifying glass will bring up the "Text Visualizer" which shows the unescaped string:

Text Visualizer

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

.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.

Replace \\ with \ in WindowsIdentity.GetCurrent().Name

There should already only be one '\'. You're misinterpreting your debugging tools showing '\' because in the underlying string is not a escape sequence '\' but a real '\' character.

Also see this StackOverflow question for some reference.

When using Visual Studio the Text Visualizer also can help. It will show the 'real' text.

Removing extra-slashes from Url in ASP.NET MVC5,

Use a Code-behind redirect in your Global.asax like this;

   protected void Application_BeginRequest(object sender, EventArgs e)
{
string requestUrl = Request.ServerVariables["REQUEST_URI"];
string rewriteUrl = Request.ServerVariables["UNENCODED_URL"];
if (rewriteUrl.Contains("//") && !requestUrl.Contains("//"))
Response.RedirectPermanent(requestUrl);
}

I got this code from This Post, I hope that's useful to you =]



Related Topics



Leave a reply



Submit