简体   繁体   中英

File is copied then complains it does not exist

I have the following code;

string oldPath = @"C:\\Users\\akclark.DOMAIN-A\\Documents\\Visual Studio 2013\\WebSites\\Quote\\quote.xlsx";
string newFileName = "" + GlobalVariables.quoteNumber + "_" + GlobalVariables.quoteRevision + ".xlsx";
string newPath = @"C:\\Users\\akclark.DOMAIN-A\\Documents\\Visual Studio 2013\\WebSites\\Quote\\" + newFileName;
FileInfo f1 = new FileInfo(oldPath);
if (f1.Exists)
{
    FileInfo f2 = new FileInfo(newPath);
    if (f2.Exists){
    File.Delete(newPath);
    } else {

        File.Copy(oldPath, newPath);
        Response.ContentType = "application/vnd.ms-excel";
        Response.AddHeader("content-length", f2.Length.ToString());
        Response.TransmitFile(newPath);
        Response.End();

    }
}

else
{
    Label20.Visible = true;
    Label20.Text = "Excel Template not found! Please Contact IT Department with this message.";
}

Everytime I run the code, it complains at Response.TransmitFile(newPath); that the file is not found.

I am running Windows 7 Pro, x64 With Visual Studio 2013 Update 2. This is .NET 4.5 Web Project.

But I just copied it three lines earlier. What am I doing wrong?

This is the problem:

@"C:\\Users\\akclark.DOMAIN-A\\Documents\\Visual Studio 2013\\WebSites\\Quote\\"

Verbatim string + double backslashes = file path with double backslashes, which could be treated by FileInfo and Response.TransmitFile differently.

Replace your code with below line

if (f2.Exists)
            {
                File.Delete(newPath);
            }
            else
            {
                File.Copy(oldPath, newPath);
                f2 = new FileInfo(newPath);
                Response.ContentType = "application/vnd.ms-excel";
                Response.AddHeader("content-length", f2.Length.ToString());
                Response.TransmitFile(newPath);
                Response.End();

            }

you code have Response.AddHeader("content-length", f2.Length.ToString()); and f2 is initialize before copy so it is unable to find and throw the error file not found.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM