如何使用UWP应用程序从文本文件中读取某一行?

时间:2016-06-07 19:28:54

标签: uwp

我如何仅从文本文件中读取第二行,其中包含位于Windows Phone SD卡上的四行或使用Visual C#编码的UWP应用程序的内部存储?

内部存储与Explorer中的Computer \ Windows phone \ Phone是否相同?

2 个答案:

答案 0 :(得分:2)

由于您的问题中没有很多细节,我将假设您需要的文件随应用程序一起部署。

public async Task<string> ReadLine(int lineIndex)
{
    var path = @"test.txt";
    var folder = Windows.ApplicationModel.Package.Current.InstalledLocation;
    var file = await folder.GetFileAsync(path);
    var lines = await Windows.Storage.FileIO.ReadLinesAsync(file);
    if (lines.Count >= lineIndex + 1)
    {
        return line[lineIndex];
    }
    else
    {
       return null;
    }
}

如果文件未随应用程序一起部署,请将文件夹属性从此处更改为另一个:Windows.Storage.ApplicationData.Current。 (LocalFolder,TempFolder,RoamingFolder)

答案 1 :(得分:-1)

Helllo,从手机内存中读取和写入文件非常简单。看看下面的示例。我演示了如何将文本文件写入IsolatedStorage然后读取它。 Hovewer如果你想从SD卡读取或写入,那里的东西就不那么明亮了。请查看MSDN文章here

        IsolatedStorageFile isoStore = IsolatedStorageFile.GetUserStoreForApplication();

        if (isoStore.FileExists("TestFile.txt"))
        {
            using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("TestFile.txt", FileMode.Open, isoStore))
            {
                using (StreamReader reader = new StreamReader(isoStream))
                {
                    var rows = reader.ReadToEnd().Split(new string[] { "\r\n" }, StringSplitOptions.None);
                    await new MessageDialog(rows[1]).ShowAsync(); //This is second row because the arrays are zero based

                }
            }
        }
        else
        {
            using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("TestFile.txt", FileMode.CreateNew, isoStore))
            {
                using (StreamWriter writer = new StreamWriter(isoStream))
                {
                    writer.WriteLine("1. Hello from first row");
                    writer.WriteLine("2. Hello from second row");
                    writer.WriteLine("3. Hello from third row");
                    writer.WriteLine("4. Hello from fourth row");
                    writer.WriteLine("5. Hello from fifth row");
                }
            }
        }