I'm creating an application in C# Universal Windows and I would like to know how would would I go about writing data to a file so that I can read from it later. I was thinking of making a class System.Serializable
and then write objects of that class as files to the user's device so then I can read those files back as objects again but I don't know how to go about doing that.
Asked
Active
Viewed 6,064 times
-2

ItzJustJosh
- 34
- 2
- 7
3 Answers
0
Use the File class. It has all the abilities you need - open a file, read its contents, edit, save or delete. From MSDN:
public static void Main()
{
string path = @"c:\temp\MyTest.txt";
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Hello");
sw.WriteLine("And");
sw.WriteLine("Welcome");
}
}
// Open the file to read from.
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}

Dido
- 520
- 2
- 7
- 21
-
Yes thanks for your answer. I am a aware of the File class and IO class as I have a background in Unity. However I don't know the proper method to do it using the Windows 10 API. Could you possibly give a small code example please. – ItzJustJosh Aug 04 '17 at 20:41
-
Done @JoshBaz :) – Dido Aug 04 '17 at 20:45
-
@JoshBaz `File` isn't related to Unity or Windows 10. It's simply part of .Net Framework. – Aug 04 '17 at 20:49
-
@Amy nah I wasn't implying that. What I meant is I got to learn about these classes by coding in Unity but I just want to know how to do the same think in this platform. – ItzJustJosh Aug 04 '17 at 20:51
0
In the .NET framework, there is a namespace called System.IO.
System.IO.StreamWriter writer = new System.IO.StreamWriter(filepath);
You can use the StreamWriter from the System.IO namespace to write to a file. The constructor simply takes in a string variable to the path of the file you want to write to. Then you can use a StreamReader (like so):
System.IO.StreamReader reader = new System.IO.StreamReader(filepath);
to read the file back again.

Expert Thinker El Rey
- 148
- 1
- 9
0
Here is an example:
class Program
{
[Serializable]
public class MyClass
{
public string Property1{ get; set; }
public string Property2 { get; set; }
}
static void Main(string[] args)
{
var item = new MyClass();
item.Property1 = "value1";
item.Property2 = "value2";
// write to file
FileStream s = new FileStream("myfile.bin", FileMode.Create);
BinaryFormatter f = new BinaryFormatter();
f.Serialize(s,item);
s.Close();
// read from file
FileStream s2 = new FileStream("myfile.bin", FileMode.OpenOrCreate,FileAccess.Read);
MyClass item2 = (MyClass)f.Deserialize(s2);
}
}

abydal
- 378
- 1
- 8