2011-03-16 57 views
1

0字节文件创建时,我试图替换C#代码背后的文件。文件保存为零字节(0字节)

string FileExactLocation = s + str; 
    if (File.Exists(FileExactLocation)) 
    { 
     File.Replace(FileExactLocation, FileExactLocation,"werwe"); 
    } 
    else 
     FileUpload1.SaveAs(FileExactLocation); 
在上面的代码

,我试图删除位于服务器上的文件,它将被删除,但我正努力拯救(替换)文件包含0字节......其空...

请给我解决这个问题....

+3

你的代码没有多大意义。为什么你想用自己替换文件? – CodesInChaos 2011-03-16 11:15:19

+0

似乎没有被刷新 – Robert 2011-03-16 11:19:51

回答

1

如果我没看错的存在内存泄漏的地方在你的代码,你想尝试使用 的“使用()”语句,也使确定你丢弃了与该文件相关的所有对象

+0

使用的关键是帮助你处理对象。谈论使用声明并且确保处理对象是多余的。 – 2011-03-16 11:21:49

+1

在上面的代码片段中,他没有创建该文件的任何实例,他只是使用'static'方法,所以没有任何处理。 – 2011-03-16 11:21:56

+0

@Tony如果我错了,纠正我,在上面提到的代码被try catch catch finally块封装,然后该对象需要像使用'using'语句一样处理,不可能使用'finally'块。 – RaM 2011-03-16 11:56:33

2

I认为你对Replace做什么感到困惑。如果您只想用新文件替换原始文件,只需删除旧文件,否则,如果您想保留原始文件的备份,请在保存之前对其进行重命名。

所以,如果我的理解是正确的,我认为你正在寻找任:

string FileExactLocation = s + str; 
    if (File.Exists(FileExactLocation)) 
    { 
     File.Delete(FileExactLocation); 
    } 
    FileUpload1.SaveAs(FileExactLocation); 

或者:

string FileExactLocation = s + str; 
    if (File.Exists(FileExactLocation)) 
    { 
     // Rename the file adding werwe to the filename 
     File.Move(FileExactLocation, Path.Combine(FileExactLocation, "werwe")); 
    } 
    FileUpload1.SaveAs(FileExactLocation); 
0

原因是fileUploadcontrol值回传后清零......和因此你创建没有数据的.zip文件.. 在这种情况下,你可以上传文件使用字节流....