开发者

File.Move making a copy of file

I have some code where I'm attempting to create a temporary file to be used as a zip file.

string tempPath = Path.GetTempFileName(); 
string targetPath = 
    string.Concat(Path.GetTempPath(),"//",Path.GetFileNameWithoutExtension(tempPath),".zip");
File.Move(tempPath, targetPath);

However a new file is being created instead of moving (renaming) the temp fil开发者_如何学运维e.

I'm definitely confused...

Kevin


I think this is what you're looking for:

FileInfo.MoveTo()

            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));
            });'


That's expected behavior. If you want the old file deleted, you need to explicitly do that.


Your code works for me.

Path.GetTempFileName()

will create a new 0 byte temporary file in your machines %TEMP% directory. After the File.Move line is run the temp file is renamed with a .zip extension.

After this you can now use the file:

using (var writeStream = new FileStream(targetPath, FileMode.Open, FileAccess.ReadWrite))
{
    // CODE HERE

}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜