Search code examples
c#delete-filetemp

File.delete not working for 'directorya\directoryb'


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)


Solution

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