简体   繁体   English

在Windows Phone 8.1的文本文件上读取和写入

[英]Reading and writing on a text file Windows Phone 8.1

My objective is to save "textbox" input to a text file and then being able to load that saved text from the same text file back to a textbox. 我的目标是将“文本框”输入保存到文本文件,然后能够将保存的文本从同一文本文件加载回文本框。

I think that one of my mistakes is reading on Console. 我认为我的一个错误就是在Console上阅读。

namespace aaa
{
    public partial class MainPage : PhoneApplicationPage
    {
        public MainPage()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            string fileName = "test.txt";

            FileStream fs = null;

            fs = new FileStream(fileName, FileMode.CreateNew);
            StreamWriter writer = new StreamWriter(fs);

            writer.Write(textBox1.Text);
        }

        private void btnWrite_Click(object sender, RoutedEventArgs e)
        {

        }

        private void btnRead_Click(object sender, RoutedEventArgs e) 
        {
            public static void Main() 
            {
                using (StreamReader sr = new StreamReader("test.txt")) 
                {
                    string line;
                    while ((line = sr.ReadLine()) != null) 
                    {
                        Console.WriteLine(line);
                    }
                }
            }
        }   
    }
}

Use Windows.Storage.StorageFile in both Windows Phone Runtime and Windows Phone Silverlight apps. 在Windows Phone运行时和Windows Phone Silverlight应用程序中使用Windows.Storage.StorageFile。

There are examples in the MSDN documentation in the Working with data and files section. 使用数据和文件”部分的MSDN文档中有一些示例。 In particular see Quickstart: Local app data or Quickstart: Roaming app data and Quickstart: Reading and writing files 特别参见快速入门:本地应用数据快速入门:漫游应用数据快速入门:读取和写入文件

This last Quickstart has demos directly on reading and writing short text snippets to a file: 最后一个快速入门直接在阅读和编写短文本片段到文件时进行演示:

// Create sample file; replace if exists.
StorageFolder folder =
    Windows.Storage.ApplicationData.Current.LocalFolder;
StorageFile sampleFile =
    await folder.CreateFileAsync("test.txt", CreationCollisionOption.ReplaceExisting);
await Windows.Storage.FileIO.WriteTextAsync(sampleFile, textBox1.text);

in windows phone you don't have such a direct access to the file system. 在Windows手机中你没有这样的文件系统直接访问权限。

you can use the isolated file storage to read and write files. 您可以使用隔离文件存储来读写文件。

here you find a broad overview of the features: 在这里您可以找到这些功能的广泛概述:

https://msdn.microsoft.com/library/system.io.isolatedstorage.isolatedstoragefile https://msdn.microsoft.com/library/system.io.isolatedstorage.isolatedstoragefile

(Caution: This is for windows phone 7, for windows phone 8.1 see the other answer) (注意:这是针对Windows Phone 7,对于Windows Phone 8.1,请参阅其他答案)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM