Domanda

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)

È stato utile?

Soluzione

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

Altri suggerimenti

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top