Rex_C
Rex_C

Reputation: 2477

Save text box data to a local file in a Windows 8 app

I'm learning how to build Windows 8 apps in XAML and I'm somewhat new to it. I have three text boxes and a button on a page and I want to take the text in each text box and save it to a file locally.

<Grid Background="{StaticResource ApplicationPageBackgroundThemeBrush}">
        <TextBox HorizontalAlignment="Left" Margin="321,160,0,0" TextWrapping="Wrap" Text="First Name" VerticalAlignment="Top"/>
        <TextBox HorizontalAlignment="Left" Margin="321,211,0,0" TextWrapping="Wrap" Text="Last Name" VerticalAlignment="Top"/>
        <TextBox HorizontalAlignment="Left" Margin="321,260,0,0" TextWrapping="Wrap" Text="Age" VerticalAlignment="Top"/>
    <Button Content="Button" HorizontalAlignment="Left" Margin="321,324,0,0" VerticalAlignment="Top"/>
</Grid>

It doesn't really matter what kind of file it is, I'm going to assume a .txt file is fairly easy to create. I've tried to wire up a FileStream on the button click, but intellisense wouldn't allow me to add the necessary usings for it. I'm starting to get the feeling that there is another way you're supposed to handle binary files in Windows 8 apps. If someone could guide me into the right documentation or quickly show me how to set it up, I'd appreciate it.

Upvotes: 0

Views: 474

Answers (1)

Matthijs
Matthijs

Reputation: 3170

A fairly easy to use method is File.WriteAllLines as shown in this topic

All you have to do now is retrieve the value from the textboxes. Make sure you assign them a Name property, so you can target them in your code-behind:

<TextBox Name="ageTextBox" HorizontalAlignment="Left" Margin="321,260,0,0" TextWrapping="Wrap" Text="Age" VerticalAlignment="Top"/>

Then in your Code-Behind, say on the button click, add the Text to a list:

List<string> myList = new List<string>();
myList.Add(ageTextBox.Text);

Finally, you write the contents of your list to a specified file:

string path = "D:\\Temp\\MyFile.txt";
File.WriteAllLines(path, myList);

Do note you have to create the eventhandler yourself, name the other textboxes and add their texts to the list too.

Upvotes: 0

Related Questions