Windows 8 Metro中文件的操作及访问(读写删除复制)

 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 ="操作失败!";

            }

        }

posted @ 2012-12-17 20:28  @大龙哥  阅读(2489)  评论(1编辑  收藏  举报