Win8Metro中,我们不能在向以前那样调用WIN32的API函数来进行文件操作,因此,下面就来介绍一下Win8 Metro中文件的读写操作。

1 Windows 8 Metro Style App中文件的操作都包含在Windows.Storage命名空间中,其中
包括StorageFolder,StorageFile,FileIO等类库
。


2 Win8文件的读写操作都是
异步方式进行的,因此要使用async

3 创建文件:

StorageFile storageFile=await Windows.Storage.KnownFolders.DocumentsLibrary.CreateFileAsync("1.txt",Windows.Storage.CreationCollisionOption.ReplaceExisting);

这里我们创建了一个1.txt的文档,如果已经存在这个文档,那么新建的文档将替换,覆盖掉旧文档。
由于文档读写是异步方式操作,因此,我们要将它放到async修饰的函数里才可以使用,具体如下:

private async void SelectImageOne(byt[] outArary)
{
StorageFile storageFile=await Windows.Storage.KnownFolders.DocumentsLibrary.CreateFileAsync("1.txt",Windows.Storage.CreationCollisionOption.ReplaceExisting);
await FileIO.WriteBytesAsync(storageFile, outArary);
}

在上述的代码中,参数是我们要写入到文件“1.txt”里的内容,这里是一个byte[]数组。

4 写入文件:


如3中的代码所示await FileIO.WriteBytesAsync(storageFile, outArary);


写入文件的方法是FileIO中的write方法,这里一共有以下四种方法:

WriteBufferAsync(Windows.Storage.IStorageFile file, IBuffer buffer);
WriteBytesAsync(Windows.Storage.IStorageFile file, byte[] buffer);
WriteLinesAsync(Windows.Storage.IStorageFile file, IEnumerable<string> lines); WriteLinesAsync(Windows.Storage.IStorageFile file, IEnumerable<string> lines, UnicodeEncoding encoding);
WriteTextAsync(Windows.Storage.IStorageFile file, string contents);
WriteTextAsync(Windows.Storage.IStorageFile file, string contents,
UnicodeEncoding encoding);

这里我们列举的是写入byte[]的方法。

5 打开文件:

StorageFile storageFile=await Windows.Storage.KnownFolders.DocumentsLibrary.CreateFileAsync("1.txt",Windows.Storage.CreationCollisionOption. OpenIfExists);

这里我们打开了一个名字为”1.txt”的文本文件。

6 读取文件:

在FileIO中有三种文件读取方法,分别读取不同的文件:

await FileIO.ReadTextAsync(Windows.Storage.IStorageFile file);
await FileIO.ReadTextAsync(Windows.Storage.IStorageFile file, UnicodeEncoding encoding);//返回指定的文本编码格式
await FileIO. ReadBufferAsync (Windows.Storage.IStorageFile file);
await FileIO. ReadLinesAsync (Windows.Storage.IStorageFile file);
await FileIO. ReadLinesAsync (Windows.Storage.IStorageFile file, UnicodeEncoding encoding);
这里我们以文本为例:
string fileIContent = await FileIO. ReadTextAsync (storageFile);
这样我们就返回了一个string文本。
我们也可以通过流来读取文件:
IBuffer buffer = await FileIO.ReadBufferAsync(storageFile); using (DataReader dataReader = DataReader.FromBuffer(buffer)) {
string fileContent = dataReader.ReadString (buffer.Length); } 7 IBuffer, byte[], Stream之间的相互转换: StorageFile storageFile=await Windows.Storage.KnownFolders.DocumentsLibrary.CreateFileAsync("1.txt",Windows.Storage.CreationCollisionOption. OpenIfExists);
IBuffer buffer = await FileIO.ReadBufferAsync(storageFile); byte[] bytes=WindowsRuntimeBufferExtensions.ToArray(buffer,0,(int)buffer.Length); Stream stream = WindowsRuntimeBufferExtensions.AsStream(buffer); 另外一个实例:
1.首先创建一个文件夹,在文件夹里创建文件
   private async void CreateButton_Click(object sender, RoutedEventArgs e)
{
    string name=FileName.Text;  //创建文件的名称
    folder =ApplicationData.Current.LocalFolder;
    StorageFolder tempFolder = await folder.CreateFolderAsync("Config",CreationCollisionOption.OpenIfExists);
file =await tempFolder.CreateFileAsync(name,CreationCollisionOption.OpenIfExists);
}
2.在创建好的文件里,写入我们的数据,这里介绍三种写入文件的方式
  private async void WriteButton_Click(object sender, RoutedEventArgs e)
{
    string content = InputTextBox.Text.Trim();
    ComboBoxItem item = WriteType.SelectedItem asComboBoxItem;  //选择写入的方式
    string type = item.Tag.ToString();
switch (type)
{
      case"1":    //以文本的方式写入文件
        await FileIO.WriteTextAsync(file,content);
        break;
      case"2":    //以bytes的方式写入文件
          Encoding encoding = Encoding.UTF8;
          byte[] bytes = encoding.GetBytes(content);
         await FileIO.WriteBytesAsync(file,bytes);
          break;
      case"3": //以流的方式写入文件
          IBuffer buffer = Convert(content);  //将string转换成IBuffer类型的
       await FileIO.WriteBufferAsync(file,buffer);
        break;
}
}
3.读取刚才写入文件里的数据,这里也介绍三种读取文件的方式
   private async void ReadButton_Click(object sender, RoutedEventArgs e)
{
      ComboBoxItem item = ReadType.SelectedItem asComboBoxItem;
   string type = item.Tag.ToString();
      string content = string.Empty;
     switch (type)
{
        case"1":        //以文本的方式读取文件
    content =await FileIO.ReadTextAsync(file);
     break;
       case"2":        //以流的方式读取文件
            IBuffer buffer = await FileIO.ReadBufferAsync(file);
     content = Convert(buffer);
          break;
       case"3":
     content =await Convert();
          break;
}
ShowTextBox.Text = content;
}
  
   private IBuffer Convert(string text)  //将string转换成IBuffer类型的
{
      using (InMemoryRandomAccessStream stream = newInMemoryRandomAccessStream())
{
        using (DataWriter dataWriter = newDataWriter())
   {
    dataWriter.WriteString(text);
            return dataWriter.DetachBuffer();
   }
}
}
  private string Convert(IBuffer buffer)    //将IBuffer转换成string类型的
{
      string text = string.Empty;
     using (DataReader dataReader=DataReader.FromBuffer(buffer))
{
   text = dataReader.ReadString(buffer.Length);
}
    return text;
}
  private async Task<string> Convert()
{
    string text=string.Empty;
     using (IRandomAccessStream readStream = await file.OpenAsync(FileAccessMode.Read))
{
        using (DataReader dataReader = newDataReader(readStream))
  {
            UInt64 size = readStream.Size;
           if (size <= UInt32.MaxValue)
     {
            UInt32 numBytesLoaded = await dataReader.LoadAsync((UInt32)size);
      text = dataReader.ReadString(numBytesLoaded);
     }
  }
}
    return text;
}
4.读取文件的属性
    private async void ReadPropertyButton_Click(object sender, RoutedEventArgs e)
{
        ComboBoxItem item = Files.SelectedItem asComboBoxItem;
       string name = item.Content.ToString();
       StorageFolder tempFolder =await Windows.Storage.ApplicationData.Current.LocalFolder.GetFolderAsync("Config");
       if (tempFolder != null)
    {
     file =await tempFolder.GetFileAsync(name);
        if (file != null)
     {
          StringBuilder builder = newStringBuilder();
      builder.AppendLine("文件名称:"+file.Name);
      builder.AppendLine("文件类型:"+file.FileType);
          BasicProperties basic = await file.GetBasicPropertiesAsync();
      builder.AppendLine("文件大小:"+basic.Size+"bytes");
     builder.AppendLine("上次修改时间:"+basic.DateModified);
      builder.AppendLine("文件路径:"+file.Path);
     List<string> list = newList<string>();
     list.Add("System.DateAccessed");
     list.Add("System.FileOwner");
            IDictionary<string, object> extra = await file.Properties.RetrievePropertiesAsync(list);
           var property = extra["System.DateAccessed"];
          if (property != null)
     {
       builder.AppendLine("文件创建时间:"+property);
    }
    property = extra["System.FileOwner"];
           if(property!=null)
    {
       builder.AppendLine("文件所有者:"+property);
     }
    DisplyProperty.Text = builder.ToString();
}
}
}
5.复制删除文件  
  private async void OKButton_Click(object sender, RoutedEventArgs e)
{
    try
{
      ComboBoxItem item=FilesList.SelectedItem asComboBoxItem;
      string fileName = item.Content.ToString();  //获得选中的文件名称
      int index=fileName.IndexOf('.');
      string firstName = fileName.Substring(0,index);
      string type = fileName.Substring(index);
      StorageFolder tempFolder = await folder.GetFolderAsync("Config");    //文件在Config文件夹下放置着
file =await tempFolder.GetFileAsync(fileName);
     if (file == null)
  {
   Msg.Text ="文件不存在!";
         return;
}
    if (CopyoButton.IsChecked.Value) //判断进行复制还是删除
{
        StorageFile copy = await file.CopyAsync(tempFolder,firstName+"复制"+type,NameCollisionOption.ReplaceExisting);
  Msg.Text ="复制成功!!!";
}
      else
{
        await file.DeleteAsync();
Msg.Text ="删除成功!!!";
}
}
  catch
{
Msg.Text ="操作失败!";
}
}

Win8 Metro中文件读写删除与复制操作的更多相关文章

  1. [WinAPI] API 9 [文件的删除、复制和移动功能]

    Windows系统为文件的删除.复制.重命名或移动文件提供了相应的API函数.删除文件使用DeleteFile函数:复制文件使用CopyFile函数:重命名文件和移动文件实际是一个操作,使用MoveF ...

  2. C++中文件读写的操作

    在C++中读读写文件一般指的就是磁盘中的文本文件和二进制文件: 文本文件:以字符序列组成的文件 二进制文件:由二进制组成的文件 读写文件采用ofstream和ifstream文件流,两者可用头文件&l ...

  3. python中文件读写

    读写文件是最常见的IO操作.Python内置了读写文件的函数,用法和C是兼容的. 读写文件前,我们先必须了解一下,在磁盘上读写文件的功能都是由操作系统提供的,现代操作系统不允许普通的程序直接操作磁盘, ...

  4. 快速入门Python中文件读写IO是如何来操作外部数据的?

    读写文件是最常见的IO操作.Python内置了读写文件的函数,用法和C是兼容的. 读写文件前,我们先必须了解一下,在磁盘上读写文件的功能都是由操作系统提供的,现代操作系统不允许普通的程序直接操作磁盘, ...

  5. 使用 windows 批处理指令(BAT文件)进行文件删除、复制操作

    以下是做文件删除和复制的批处理指令 ::替换文件需要添加 /y 参数才能直接替换.不然会出现提示是否替换. ::复制Axis2Implementation和WebServices编译后的文件到tomc ...

  6. Python基础笔记系列十一:标准输入输出、文件读写和指针等操作

    本系列教程供个人学习笔记使用,如果您要浏览可能需要其它编程语言基础(如C语言),why?因为我写得烂啊,只有我自己看得懂!! 标准输入输出一.输入 在sublime中这个时候需要安装SublimeRE ...

  7. C和C++中文件读写的区别

    C中采用的主要是文件指针的办法,C++中对文件的操作主要运用了“文件流”(即非标准的输入输出)的思想 eg1": #include<stdio.h> //... FILE* fp ...

  8. (原)Eclipse的java中文件读写

    1 在<uses-sdk…/>下面添加permission <uses-sdk android:minSdkVersion="16" android:target ...

  9. Python中文件读写之 w+ 与 r+ 到底有啥区别?

    其实r 是只读,只能读不能写,这是很明确的,但是r+是可读写,变成r+后还没太明白到底加了什么,还是照样写不了,有没有这样的体验呢,如下代码,只读时 f = open("test.txt&q ...

随机推荐

  1. HDU 1829 A Bug's Life 【带权并查集/补集法/向量法】

    Background Professor Hopper is researching the sexual behavior of a rare species of bugs. He assumes ...

  2. 洛谷——P1113 杂务

    P1113 杂务 题目描述 John的农场在给奶牛挤奶前有很多杂务要完成,每一项杂务都需要一定的时间来完成它.比如:他们要将奶牛集合起来,将他们赶进牛棚,为奶牛清洗乳房以及一些其它工作.尽早将所有杂务 ...

  3. 关于matplotlib,你要的饼图在这里

    Table of Contents 1  官方Demo 2  将实际数据应用于官方Demo 3  一些改善措施 3.1  重新设置字体大小 3.2  设置显示颜色,Method 1: 3.3  设置显 ...

  4. [拒绝毒瘤的小清新系列] give you a tree

    题面在这里! (小声)这其实是我读错某题之后自己出的一道题...... 正解也很简单啦,直接扫描线+线段树水过(考虑一个合法的区间正好有 siz-1 对树上相邻的点对)23333 #include&l ...

  5. HihoCoder - 1715 树的连通问题

    题面在这里! 正式告别文化课回归的第一题QWQ,然鹅半个月之后还是要退役QWQWQWQWQ 好像很久之前就见过的一个题,当时只会打一打 O(N^2) 的暴力QWQ,正好今天又写了遍这个暴力用来对拍23 ...

  6. BZOJ 3289 Mato的文件管理(莫队+树状数组)

    [题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=3289 [题目大意] 求静态区间逆序对. [题解] 我们对查询进行莫队操作,对于区间的删 ...

  7. BZOJ 1123 [POI2008]BLO(Tarjan算法)

    [题目链接] http://www.lydsy.com/JudgeOnline/problem.php?id=1123 [题目大意] Byteotia城市有n个towns,m条双向roads. 每条r ...

  8. 【朱-刘算法】【最小树形图】hdu6141 I am your Father!

    题意:给你一张带权有向图,让你求最大树形图.并在此前提下令n号结点父亲的编号最小. 比赛的时候套了个二分,TLE了. 实际上可以给每个边的权值乘1000,对于n号结点的父边,加上(999-父结点编号) ...

  9. Semaphore(信号量)源码分析

    1. Semaphore Semaphore和ReentrantReadWriteLock.ReadLock(读锁)都采用AbstractOwnableSynchronizer共享排队的方式实现. 关 ...

  10. [转]详解spring 每个jar的作用

    spring.jar 是包含有完整发布模块的单个jar 包.但是不包括mock.jar, aspects.jar, spring-portlet.jar, and spring-hibernate2. ...