Windows Phone 八、文件读写IO

时间:2022-01-12 03:17:26
文件存储的类型
•本地应用文件:
•ApplicationData.Current.LocalFolder;
•漫游应用文件:
•ApplicationData.Current.RoamingFolder;
•临时应用文件:
•ApplicationData.Current.TemporaryFolder;
文件IO
     <StackPanel>
<StackPanel Orientation="Horizontal">
<Button
x:Name="btnSave"
Content="Save"
Click="btnSave_Click"/>
<Button
x:Name="btnGet"
Content="Get"
Click="btnGet_Click"/>
</StackPanel>
<TextBlock x:Name="txt" Height="500"/>
</StackPanel>
 //拿到本地文件夹对象
StorageFolder folder = ApplicationData.Current.LocalFolder;
private async void btnSave_Click(object sender, RoutedEventArgs e)
{
//写入操作
var text = txt.Text;
//通过文件夹创建文件
var file = await folder.CreateFileAsync("temp.txt", CreationCollisionOption.ReplaceExisting);
//写入文本到文件中,仅适用于小文件写入
//await FileIO.AppendTextAsync(file, text);//小文件读写 //使用文件流的形式写入文件
using (var stream = await file.OpenStreamForWriteAsync())
{
using (var writer = new StreamWriter(stream))
{
await writer.WriteAsync(text);
}
}
}
private async void btnGet_Click(object sender, RoutedEventArgs e)
{
//打开一个现有文件,注意:没有文件则报异常
var file = await folder.GetFileAsync("temp.txt");
//var text = await FileIO.ReadTextAsync(file);
//txt.Text = text; //使用文件流去读取文件
using (var stream = await file.OpenStreamForReadAsync())
{
using (var reader = new StreamReader(stream))
{
txt.Text = await reader.ReadToEndAsync();
}
}
}
拷贝和剪切

//获取本地文件夹对象

var localFolder = ApplicationData.Current.LocalFolder;

//根据文件名获取文件对象

var file = await localFolder.GetFileAsync("temp.txt");

//拷贝目标文件夹

var myFolder = await localFolder.CreateFolderAsync("MyFolder", CreationCollisionOption.OpenIfExists);

//拷贝到制定文件夹

var newFile = await file.CopyAsync(myFolder, "new.txt",NameCollisionOption.ReplaceExisting);

//移动到新路径

await file.MoveAsync(myFolder);

删除和重命名

//获取本地文件夹对象

var localFolder = ApplicationData.Current.LocalFolder;

//根据文件名获取文件对象

var file = await localFolder.GetFileAsync("temp.txt");

//对文件进行重命名操作

await file.RenameAsync("temp2.txt");

//删除文件

await file.DeleteAsync();