上传文件时出现“进程无法访问文件,因被其他进程占用”错误
解决“进程无法访问文件,因为它正被另一个进程使用”的问题
可能的原因及修复步骤
1. 源文件被其他进程锁定
如果computerservice.db正被你的程序其他模块(比如数据库连接)或外部工具(如数据库查看器)占用,File.Copy或后续上传操作会因文件锁定失败。
- 修复:执行复制前,关闭所有打开该文件的连接或进程。比如用
using包裹数据库连接,确保连接自动释放:using(var conn = new SQLiteConnection("Data Source=computerservice.db")) { // 数据库操作 }
2. 清理无用代码并确保目标目录存在
CopyDBForService里初始化的FolderBrowserDialog完全未使用,属于冗余代码,可能引发未知资源占用;同时要确保目标目录存在,避免复制时抛出额外错误:
private static void CopyDBForService() { var srcFile = "computerservice.db"; var destFile = "./Service/computerservice.db"; // 确保目标目录存在 Directory.CreateDirectory(Path.GetDirectoryName(destFile)); File.Copy(srcFile, destFile, true); }
3. 确认目标文件可访问后再上传
极少数情况下,File.Copy完成后系统文件缓存可能暂时锁定文件,可添加等待逻辑确认文件可访问:
private static void WaitForFileAccess(string filePath) { int attempts = 0; while (attempts < 10) { try { using (var stream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) { break; } } catch (IOException) { attempts++; Thread.Sleep(100); } } }
修改上传方法调用该逻辑:
private static void UpdateDBAsync() { CopyDBForService(); var destFile = "./Service/computerservice.db"; WaitForFileAccess(destFile); try { using var client = new WebClient(); client.Credentials = new NetworkCredential(username, password); client.UploadFile("ftp://example.com/computerservice.db", WebRequestMethods.Ftp.UploadFile, destFile); } catch (WebException e) { String status = ((FtpWebResponse)e.Response).StatusDescription; MessageBox.Show(status); } }
4. 排查目标文件的其他访问进程
确认上传期间没有其他服务或程序读取./Service/computerservice.db文件,比如你的后台服务如果正在监控该文件,会导致上传时锁定冲突。
内容的提问来源于stack exchange,提问作者Елизавета Левина
相关产品推荐
相关产品推荐

