0

这基本上适用于 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);

但是当我运行这个程序时,它会抛出一个错误“访问被拒绝或我们无法访问文件”。使用这种方法,我正在编写许多文件并阅读。请让我知道如何解决这个问题。提前致谢

我的问题是当我访问文件以读取和显示当时文件涉及写入过程,这就是为什么我无法访问该文件并且它显示错误的原因。所以。有没有什么方法可以让我们只在文件写入过程完成并且读取过程开始时才继续前进?

4

1 回答 1

1

您可以使用SemaphoreSlimwhich 限制可以访问资源的线程数。下面是一个处理文件写入/读取的类的示例。当您要写入文件并调用 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 进行写入/读取,但是您一次只能写入/读取一个文件(这可能不是问题)。

于 2013-07-25T21:40:04.537 回答