[英]File.Move making a copy of file
我有一些代碼試圖在其中創建一個臨時文件以用作zip文件。
string tempPath = Path.GetTempFileName();
string targetPath =
string.Concat(Path.GetTempPath(),"//",Path.GetFileNameWithoutExtension(tempPath),".zip");
File.Move(tempPath, targetPath);
但是,將創建一個新文件,而不是移動(重新命名)臨時文件。
我肯定很困惑...
凱文
我認為這是您要尋找的:
var newFiles = System.IO.Directory.GetFiles(updateLocation).Select(file => new FileInfo(file));
var workingDirectory = Environment.CurrentDirectory;
var existingFiles = System.IO.Directory.GetFiles(workingDirectory).Select(file => new FileInfo(file));
newFiles.ToList().ForEach(newFile =>
{
var matchedFile = existingFiles.ToList().Find(delegate(FileInfo file) { return file.Name == newFile.Name; });
if(matchedFile != null)
{
if(newFile.LastWriteTimeUtc != matchedFile.LastWriteTimeUtc)
{
if(!Directory.Exists(TEMP_DIRECTORY_NAME))
Directory.CreateDirectory(TEMP_DIRECTORY_NAME);
matchedFile.MoveTo(Path.Combine(TEMP_DIRECTORY_NAME, matchedFile.Name));
newFile.CopyTo(Path.Combine(workingDirectory, newFile.Name));
}
}
else
newFile.CopyTo(Path.Combine(workingDirectory, newFile.Name));
});'
這是預期的行為。 如果要刪除舊文件,則需要明確地執行此操作。
您的代碼對我有用。
Path.GetTempFileName()
將在您的計算機%TEMP%目錄中創建一個新的0字節臨時文件。 運行File.Move行之后,臨時文件將以.zip擴展名重命名。
之后,您現在可以使用文件:
using (var writeStream = new FileStream(targetPath, FileMode.Open, FileAccess.ReadWrite))
{
// CODE HERE
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.