UWP应用读取WebCacheV01.dat失败:文件被占用求只读解决方案
UWP读取WebCacheV01.dat文件被占用的只读解决方案
问题描述
尝试在UWP应用中读取WebCacheV01.dat文件时,执行FileIO.ReadLinesAsync(file)出现错误:
The process cannot access the file because it is being used by another process
该文件被系统相关进程(如Windows缓存服务)独占锁定,需通过特定只读策略绕过占用限制。
解决办法
1. 启用共享只读模式打开文件流
FileIO.ReadLinesAsync默认未启用共享读取权限,手动指定共享只读模式可允许在其他进程占用文件时进行只读访问:
var filePath = @"C:\Users\adm\AppData\Local\Microsoft\Windows\WebCache\WebCacheV01.dat"; StorageFile file = await StorageFile.GetFileFromPathAsync(filePath); if (file != null) { // 以只读+共享读取模式打开文件流 using (var stream = await file.OpenAsync(FileAccessMode.Read, StorageOpenOptions.SharedRead)) { using (var reader = new StreamReader(stream.AsStreamForRead())) { List<string> lines = new List<string>(); string line; while ((line = await reader.ReadLineAsync()) != null) { lines.Add(line); } // 在此处理读取到的内容 } } }
2. 复制文件到应用本地目录后读取
若共享读取模式仍失败(部分系统进程会强制独占锁定文件),可先将原文件复制到UWP应用有权限访问的本地目录,再读取副本:
var sourcePath = @"C:\Users\adm\AppData\Local\Microsoft\Windows\WebCache\WebCacheV01.dat"; StorageFile sourceFile = await StorageFile.GetFileFromPathAsync(sourcePath); // 获取应用本地存储目录 var localFolder = ApplicationData.Current.LocalFolder; // 复制文件到本地目录,覆盖已存在的副本 var copiedFile = await sourceFile.CopyAsync(localFolder, "WebCacheCopy.dat", NameCollisionOption.ReplaceExisting); // 读取复制后的文件 using (var stream = await copiedFile.OpenReadAsync()) { using (var reader = new StreamReader(stream.AsStreamForRead())) { string content = await reader.ReadToEndAsync(); IList<string> lines = content.Split(new[] { Environment.NewLine }, StringSplitOptions.None).ToList(); // 在此处理读取到的内容 } }
3. 配置UWP应用文件访问权限
访问用户AppData目录下的文件需开启广泛文件系统访问权限:
- 在
Package.appxmanifest中添加权限声明:<Capabilities> <Capability Name="broadFileSystemAccess" /> </Capabilities> - 打开系统设置 → 应用 → 找到目标UWP应用 → 权限 → 开启「文件系统」权限。
内容的提问来源于stack exchange,提问作者ATAO
相关产品推荐
相关产品推荐

