这基本上适用于Windows 8应用程序,我正在使用此方法编写文件 -
static async void WriteDataCords(int numDataCodewords)
{
StorageFolder storageFolder = KnownFolders.DocumentsLibrary;
var storageFile = await storageFolder.GetFileAsync("DataCodeWords.txt");
string data = numDataCodewords.ToString();
await FileIO.AppendTextAsync(storageFile, data);
}
现在我正在使用这种方法读取文件 -
StorageFolder storageFolder7 = KnownFolders.DocumentsLibrary;
var storageFile7 = await storageFolder6.GetFileAsync("DataCodeWords.txt");
string text7 = await Windows.Storage.FileIO.ReadTextAsync(storageFile7);
但是当我运行这个程序时,它会抛出错误“访问被拒绝或我们无法访问该文件”。使用这种方法我写了很多文件和阅读。请让我知道如何解决这个问题。 提前致谢
我的问题是当我访问文件时要读取并显示当时文件涉及写入过程,这就是为什么我无法访问该文件并且显示错误。 所以。有没有什么方法可以在文件编写过程完成时向前推进,而不是开始读取过程?
答案 0 :(得分:1)
您可以使用SemaphoreSlim
来限制可以访问资源的线程数。
下面是一个处理文件写入/读取的类的示例。当您要编写文件并调用WriteDataCords方法时,可以创建它的实例。然后,当您想要读取然后调用ReadDataCords时,您需要一些方法来访问正确的实例:
public class FileReadWrite
{
public string FileName { get; set; }
public FileReadWrite(string fileName)
{
FileName = fileName;
}
private readonly SemaphoreSlim _semaphore = new SemaphoreSlim(1, 1);
public async Task WriteDataCords(int numDataCodewords)
{
await _semaphore.WaitAsync();
try
{
StorageFolder storageFolder = KnownFolders.DocumentsLibrary;
var storageFile = await storageFolder.GetFileAsync(FileName);
string data = numDataCodewords.ToString();
await FileIO.AppendTextAsync(storageFile, data);
}
finally
{
_semaphore.Release();
}
}
public async Task ReadDataCords()
{
await _semaphore.WaitAsync();
try
{
StorageFolder storageFolder6 = KnownFolders.DocumentsLibrary;
var storageFile7 = await storageFolder6.GetFileAsync(FileName);
string text7 = await Windows.Storage.FileIO.ReadTextAsync(storageFile7);
}
finally
{
_semaphore.Release();
}
}
}
并致电代码:
public class ClientCode
{
public async void WriteFile()
{
var fileReadWrite = new FileReadWrite("DataCodeWords.txt");
await fileReadWrite.WriteDataCords(42);
}
public async void ReadFile()
{
var fileReadWrite = GetFileReadWriteForFile("DataCodeWords.txt"); //Method for retreiving correct instance of FileWriteRead class
await fileReadWrite.ReadDataCords();
}
private FileReadWrite GetFileReadWriteForFile(string fileName)
{
}
}
你可以跳过FileWriteRead类(它增加了复杂性)并在原始代码中直接使用SemaphoreSlim进行写入/读取,但是你一次只能写/读一个文件(这可能不是问题)。