读写文件时总是各种Stream让我迷糊,Stream到底是个什么东西(我理解Stream为文件句柄不知道对不对)。
以下代码是林政老师讲课里面的2中方法写文件,不知道有啥区别?
public async Task WriteLocalFile(string fileName, string text)
{
StorageFolder storageFolder = ApplicationData.Current.LocalFolder;//获取本地文件夹/目录
//创建文件
StorageFile storageFile = await storageFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (Stream stream = await storageFile.OpenStreamForWriteAsync())
{
byte[] content = Encoding.UTF8.GetBytes(text);
await stream.WriteAsync(content, 0, content.Length);//把text内容写入到文件中
}
}
public async Task WriteToFile(string fileName, string contents, StorageFolder folder = null)
{
folder = folder?? ApplicationData.Current.LocalFolder;
StorageFile file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (IRandomAccessStream fileAccessStream = await file.OpenAsync(FileAccessMode.ReadWrite))
{
using (IOutputStream outStream = fileAccessStream.GetOutputStreamAt(0))
{
using (var dataWriter = new DataWriter(outStream))
{
if (null != contents)
{
dataWriter.WriteString(contents);
}
await dataWriter.StoreAsync();
dataWriter.DetachStream();
}
await outStream.FlushAsync();
}
}
}
------解决思路----------------------
你可以理解为Stream是水管,你要读写的数据(当然也包含文件)就是水,你上面的例子可以理解为水从内存这个水池流向独立存储的水池。
至于你说的两种写法(其实还有其他很多种方法),只是类库提供的不同接口而已,就好比把水从一个水池导入到另一个水池可以用水管1,也可以用水管2,3,4,5,,,n等等。