gpt4 book ai didi

c# - File.Delete 问题与 filestream.write()

转载 作者:太空宇宙 更新时间:2023-11-03 15:43:25 26 4
gpt4 key购买 nike

我有刷新按钮。刷新时,我需要下载一个文件并反序列化其内容以读取其中的信息。以下是用于下载文件的方法。

public void DownloadVersionContents(long fileID,string fileName)
{
if (File.Exists(path))
{
File.Delete(path);
}
Stream stream = service.DownloadContent(fileID);

using (FileStream fileStream = File.OpenWrite(fileName))
{
// Write the stream to the file on disk.
var buf = new byte[1024];
int numBytes;
while ((numBytes = stream.Read(buf, 0, buf.Length)) > 0)
{
fileStream.Write(buf, 0, numBytes);
}
fileStream.Close();
}
stream.Close();
}

每次单击刷新按钮时,我都必须删除文件并从服务器下载最新文件。如果在一两秒内调用刷新,我会收到一条错误消息

System.IO.IOException was caught
HResult=-2147024864
Message=The process cannot access the file 'C:\Users\...\AppData\Local\Temp\mapping - copy.xml' because it is being used by another process.
Source=mscorlib
StackTrace:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.File.InternalDelete(String path, Boolean checkHost)
at System.IO.File.Delete(String path)

如果在至少 10 或 20 秒后调用刷新,我不会收到任何错误。该文件从未打开或使用过。请帮忙。编辑:抱歉,我忘了说,我在调用刷新后立即使用此方法反序列化文件。

public static T DeSerializeFromFile<T>(string xmlFilePath) 
{
T instance = default(T);

if (xmlFilePath != null)
{
var reader = new StreamReader(xmlFilePath);
var serializer = new XmlSerializer(typeof(T));
instance = (T)serializer.Deserialize(reader);
}
return instance;
}

更新值后再次调用刷新按钮。

最佳答案

这似乎是使用 try catch block 的好时机。捕获异常并在文件繁忙时提示用户。

try
{
if (File.Exists(path))
File.Delete(path);

using(Stream stream = service.DownloadContent(fileID))
{
using (FileStream fileStream = File.OpenWrite(fileName))
{
// Write the stream to the file on disk.
var buf = new byte[1024];
int numBytes;
while ((numBytes = stream.Read(buf, 0, buf.Length)) > 0)
{
fileStream.Write(buf, 0, numBytes);
}
}
}
}
catch (IOException e)
{
MessageBox.Show("The refresh failed, try again in a few seconds.");
}

这不会加快刷新过程,但会防止用户通过垃圾刷新使您的程序崩溃。尝试在使用外部资源时始终存在这种异常处理。

关于c# - File.Delete 问题与 filestream.write(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29296902/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com