如何在Windows 8 metro App中读取文件

时间:2012-09-21 08:51:52

标签: file-io windows-8 microsoft-metro

我想发送一个文本文件和我的应用程序,并在执行我的应用程序时读取它。我该如何阅读该特定文件?我已将文件设置为内​​容并在较新时复制。

2 个答案:

答案 0 :(得分:4)

private async void ProjectFile()
{
    var _Path = @"Metro.Helpers.Tests\MyFolder\MyFolder.txt";
    var _Folder = Windows.ApplicationModel.Package.Current.InstalledLocation;

    var _File = await _Folder.GetFileAsync(_Path);
    var _ReadThis = await Windows.Storage.FileIO.ReadTextAsync(_File);
}

读取适合我的项目文件的代码。希望它也有助于其他人:)

答案 1 :(得分:2)

您的问题的答案在很大程度上取决于您想要阅读文件的 以及它包含的内容。

您可以在File Access Sample app on MSDN中找到一些文件访问示例,其中一个示例是:

if (file != null) 
{ 
    using (IRandomAccessStream readStream = await file.OpenAsync(FileAccessMode.Read)) 
    { 
        using (DataReader dataReader = new DataReader(readStream)) 
        { 
            UInt64 size = readStream.Size; 
            if (size <= UInt32.MaxValue) 
            { 
                UInt32 numBytesLoaded = await dataReader.LoadAsync((UInt32)size); 
                string fileContent = dataReader.ReadString(numBytesLoaded); 
                OutputTextBlock.Text = "The following text was read from '" + file.Name + "' using a stream:" + Environment.NewLine + Environment.NewLine + fileContent; 
            } 
            else 
            { 
                OutputTextBlock.Text = "File " + file.Name + " is too big for LoadAsync to load in a single chunk. Files larger than 4GB need to be broken into multiple chunks to be loaded by LoadAsync."; 
            } 
        } 
    } 
}