Reading and writing on a text file Windows Phone 8.1

给你一囗甜甜゛ 提交于 2019-12-10 16:58:24

问题


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.

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);
                    }
                }
            }
        }   
    }
}

回答1:


Use Windows.Storage.StorageFile in both Windows Phone Runtime and Windows Phone Silverlight apps.

There are examples in the MSDN documentation in the Working with data and files section. 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);



回答2:


in windows phone you don't have such a direct access to the file system.

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

(Caution: This is for windows phone 7, for windows phone 8.1 see the other answer)



来源:https://stackoverflow.com/questions/30669491/reading-and-writing-on-a-text-file-windows-phone-8-1

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!