在windows store app 开发过程中,经常需要进行文件的读写操作,下面给出的是一些简单的文件读写,仅供参考
1.简单的文件写入操作
private async void write()
{
StorageFolder storagefolder = ApplicationData.Current.LocalFolder;//获取文件夹路径
StorageFile storagefile = null;
storagefile = await storagefolder .CreateFileAsync(“Me.txt”, CreationCollisionOption.ReplaceExisting);//在指定路径下创建文件(可重写)
if (storagefile !=null)
{
using (Stream stream = await storagefile.OpenStreamForWriteAsync())
{
byte[] content= Encoding.UTF8.GetBytes(“Hello World !”);
await stream.WriteAsync(content, 0, content.Length);//数据写入
}
}
else
{
//文件没找到
}
}
这样,到程序的工作目录下,就可以看到一个名为Me.txt的文本文件,打开文件,明晃晃的几个大字:Hello World !
我们既然已经可以将数据写入到文件中,那么又如何读取文件中的内容呢,我们继续文件的读取操作
2.简单的文件读取操作
private async void read()
{
StorageFolder storagefolder = ApplicationData.Current.LocalFolder;//获取文件夹路径
StorageFile storagefile = null;
storagefile = await storagefolder .GetFileAsync(“Me.txt”);
if (storagefile != null)
{
IRandomAccessStreamWithContentType readstream = await storageFile.OpenReadAsync();
using (Stream stream = readstream.AsStreamForRead((int)readstream.Size))
{
byte[] content = new byte[stream.Length];
await stream.ReadAsync(content, 0, (int)stream.Length);
string readcontent = Encoding.UTF8.GetString(content, 0, content.Length);//文件内容读取
}
}
else
{
//未找到文件
}
}
以上就是简单的文件读取,不要忘记
using Windows.Storage;
using Windows.Storage.Streams;