Jason Brown
Jason Brown

Reputation: 109

Writing to and reading from a text file - C# Windows Universal Platform App Windows 10

********IT WORKS! But you have to type in the TextBox before anything shows. I guess that's because I used the 'TextChanged' event handler. Which event handler do I use if I want it to show the contents of the text file without user interaction?********

So I want to write some data to a text file in a C# Windows 10 Universal Platform App when a button is pressed, and I want a TextBlock or a TextBox to read the contents of that text file in my app.

I'm using a pivot-style app, the button to write the file is on one pivot and the TextBlock or TextBox I want to contain the contents of the text file is on another pivot.

My code is below. It doesn't work. I'm not sure it's even creating and writing the file and there is nothing in either my TextBox or TextBlock. :(

I got the code from here: https://msdn.microsoft.com/en-us/library/windows/apps/mt185401.aspx

Code to write the file:

private async void submitButton_Click(object sender, RoutedEventArgs e)
    {
        //WRITE THE TICKET TO A LOCAL DATABASE (txt)//

        //Create the text file to hold the data
        Windows.Storage.StorageFolder storageFolder =
            Windows.Storage.ApplicationData.Current.LocalFolder;
        Windows.Storage.StorageFile ticketsFile =
            await storageFolder.CreateFileAsync("tickets.txt",
                Windows.Storage.CreationCollisionOption.ReplaceExisting);

        //Write data to the file
        await Windows.Storage.FileIO.WriteTextAsync(ticketsFile, "Swift as a shadow");
    }

Code to read the file in a TextBox:

private async void viewTickets_TextChanged(object sender, TextChangedEventArgs e)
    {
        Windows.Storage.StorageFolder storageFolder =
            Windows.Storage.ApplicationData.Current.LocalFolder;
        Windows.Storage.StorageFile ticketsFile =
            await storageFolder.GetFileAsync("tickets.txt");

        string savedTickets = await Windows.Storage.FileIO.ReadTextAsync(ticketsFile);

        viewTickets.Text = savedTickets; 
    }

Upvotes: 6

Views: 9434

Answers (2)

guest
guest

Reputation: 125

public async Task WriteToDictionaryAsync(Dictionary<string, string> dictionary, StorageFile binarySourceFile)
    {
        await Task.Delay(5);
        using (FileStream fs = File.OpenWrite(binarySourceFile.Path))
        using (BinaryWriter writer = new BinaryWriter(fs))
        {
            // Put count.
            writer.Write(dictionary.Count);
            // Write pairs.
            foreach (var pair in dictionary)
            {
                writer.Write(pair.Key);
                writer.Write(pair.Value);
            }
        }
    }
    public async void WriteToDictionary(Dictionary<string, string> dictionary, StorageFile binarySourceFile)
    {
        await Task.Delay(5);
        using (FileStream fs = File.OpenWrite(binarySourceFile.Path))
        using (BinaryWriter writer = new BinaryWriter(fs))
        {
            // Put count.
            writer.Write(dictionary.Count);
            // Write pairs.
            foreach (var pair in dictionary)
            {
                writer.Write(pair.Key);
                writer.Write(pair.Value);
            }
        }
    }
    public async Task<Dictionary<string, string>> ReadDictionaryAsync(StorageFile binarySourceFile)
    {
        await Task.Delay(5);
        var result = new Dictionary<string, string>();
        using (FileStream fs = File.OpenRead(binarySourceFile.Path))
        using (BinaryReader reader = new BinaryReader(fs))
        {
            // Get count.
            int count = reader.ReadInt32();
            // Read in all pairs.
            for (int i = 0; i < count; i++)
            {
                string key = reader.ReadString();
                string value = reader.ReadString();
                result[key] = value;
            }
        }
        return result;
    }
    public Dictionary<string, string> ReadDictionary(StorageFile binarySourceFile)
    {
        var result = new Dictionary<string, string>();
        using (FileStream fs = File.OpenRead(binarySourceFile.Path))
        using (BinaryReader reader = new BinaryReader(fs))
        {
            // Get count.
            int count = reader.ReadInt32();
            // Read in all pairs.
            for (int i = 0; i < count; i++)
            {
                string key = reader.ReadString();
                string value = reader.ReadString();
                result[key] = value;
            }
        }
        return result;
    }

//Create bin File var binarySourceFile = await StorageData.LocalFolder.CreateFileAsync("binFile" + ".bin", CreationCollisionOption.ReplaceExisting);

Upvotes: 0

Shaharyar
Shaharyar

Reputation: 12449

Your code is perfectly fine, the only problem is it doesn't get executed. When you click on the button your file is created. But you don't type anything in the textbox so you never read the file.

I think you want to read it immediately after writing it. Put your Read file code right after the Write code:

private async void submitButton_Click(object sender, RoutedEventArgs e)
{
    //WRITE THE TICKET TO A LOCAL DATABASE (txt)//

    //Create the text file to hold the data
    Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
    Windows.Storage.StorageFile ticketsFile = await storageFolder.CreateFileAsync("tickets.txt", Windows.Storage.CreationCollisionOption.ReplaceExisting);

    //Write data to the file
    await Windows.Storage.FileIO.WriteTextAsync(ticketsFile, "Swift as a shadow");

    //read file
    string savedTickets = await Windows.Storage.FileIO.ReadTextAsync(ticketsFile);

    viewTickets.Text = savedTickets;
}

and remove the viewTickets_TextChanged event handler.

Upvotes: 9

Related Questions