使用 .NET的IO(5) Paul

查找现有的文件和目录

您还可以使用独立存储文件来搜索现有的目录和文件。请记住,在存储区中,文件名和目录名是相对于虚文件系统的根目录指定的。此外,Windows 文件系统中的文件和目录名不区分大小写。
要搜索某个目录,请使用 IsolatedStorageFile 的 GetDirectoryNames 实例方法。GetDirectoryNames 采用表示搜索模式的字符串。支持使用单字符 (?) 和多字符 (*) 通配符。这些通配符不能出现在名称的路径部分。也就是说,directory1/*ect* 是有效的搜索字符串,而 *ect*/directory2 不是有效的搜索字符串。
要搜索某个文件,请使用 IsolatedStorageFile 的 GetFileNames 实例方法。对应用于 GetDirectoryNames 的搜索字符串中通配符的相同限制也适用于 GetFileNames
GetDirectoryNamesGetFileNames 都不是递归的,即 IsolatedStorageFile 不提供用于列出存储区中所有目录或文件的方法。但是,下面的代码中部分是递归方法的示例。另外还要注意,GetDirectoryNamesGetFileNames 只返回找到的项的目录名或文件名。例如,如果找到目录 RootDir/SubDir/SubSubDir 的匹配项,结果数组中将返回 SubSubDir。

FindingExistingFilesAndDirectories 示例

下面的代码示例阐释如何在独立存储区创建文件和目录。首先,检索一个按用户、域和程序集隔离的存储区并放入 isoStore 变量。CreateDirectory 方法用于设置几个不同的目录,IsolatedStorageFileStream 方法在这些目录中创建一些文件。然后,代码依次通过 GetAllDirectories 方法的结果。该方法使用 GetDirectoryNames 来查找当前目录中的所有目录名。这些名称存储在数组中,然后 GetAllDirectories 调用其本身,传入它所找到的每个目录。结果是在数组中返回的所有目录名。然后,代码调用 GetAllFiles 方法。该方法调用 GetAllDirectories 以查找所有目录的名称,然后它检查每个目录以查找使用 GetFileNames 方法的文件。结果返回到数组中用于显示。

 [C#]
using System;
using System.IO;
using System.IO.IsolatedStorage;
using System.Collections;
 
public class FindingExistingFilesAndDirectories{
 
   // Retrieves an array of all directories in the store, and 
   // displays the results.
 
   public static void Main(){
 
      // This part of the code sets up a few directories and files in the
      // store.
      IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);
      isoStore.CreateDirectory("TopLevelDirectory");
      isoStore.CreateDirectory("TopLevelDirectory/SecondLevel");
      isoStore.CreateDirectory("AnotherTopLevelDirectory/InsideDirectory");
      new IsolatedStorageFileStream("InTheRoot.txt", FileMode.Create, isoStore);
      new IsolatedStorageFileStream("AnotherTopLevelDirectory/InsideDirectory/HereIAm.txt", FileMode.Create, isoStore);
      // End of setup.
 
      Console.WriteLine('\r');
      Console.WriteLine("Here is a list of all directories in this isolated store:");
 
      foreach(string directory in GetAllDirectories("*", isoStore)){
         Console.WriteLine(directory);
      }
      Console.WriteLine('\r');
 
      // Retrieve all the files in the directory by calling the GetFiles 
      // method.
 
      Console.WriteLine("Here is a list of all the files in this isolated store:");
      foreach(string file in GetAllFiles("*", isoStore)){
         Console.WriteLine(file);
      }  
 
   }// End of Main.
  
   // Method to retrieve all directories, recursively, within a store.
 
   public static string[] GetAllDirectories(string pattern, IsolatedStorageFile storeFile){
 
      // Get the root of the search string.
 
      string root = Path.GetDirectoryName(pattern);
 
      if (root != "") root += "/";
 
      // Retrieve directories.
 
      string[] directories;
 
      directories = storeFile.GetDirectoryNames(pattern);
 
      ArrayList directoryList = new ArrayList(directories);
 
      // Retrieve subdirectories of matches.
 
      for (int i = 0, max = directories.Length; i < max; i++){
         string directory = directoryList[i] + "/";
         string[] more = GetAllDirectories (root + directory + "*", storeFile);
 
         // For each subdirectory found, add in the base path.
 
         for (int j = 0; j < more.Length; j++)
            more[j] = directory + more[j];
 
         // Insert the subdirectories into the list and 
         // update the counter and upper bound.
 
         directoryList.InsertRange(i+1, more);
         i += more.Length;
         max += more.Length;
      }
 
      return (string[])directoryList.ToArray(Type.GetType("System.String"));
   }
 
   public static string[] GetAllFiles(string pattern, IsolatedStorageFile storeFile){
 
      // Get the root and file portions of the search string.
 
      string fileString = Path.GetFileName(pattern);
 
      string[] files;
      files = storeFile.GetFileNames(pattern);
 
      ArrayList fileList = new ArrayList(files);
 
      // Loop through the subdirectories, collect matches, 
      // and make separators consistent.
 
      foreach(string directory in GetAllDirectories( "*", storeFile))
         foreach(string file in storeFile.GetFileNames(directory + "/" + fileString))
            fileList.Add((directory + "/" + file));
 
      return (string[])fileList.ToArray(Type.GetType("System.String"));
         
   }// End of GetFiles.
 
}

读取和写入文件

使用 IsolatedStorageFileStream 类,有多种方法可以打开存储区中的文件。一旦获得了 IsolatedStorageFileStream 之后,可使用它来获取 StreamReader 或 StreamWriter。使用 StreamReaderStreamWriter,您可以像对任何其他文件一样读取和写入存储区中的文件。

ReadingAndWritingToFiles 示例

下面的代码示例获得独立存储区,创建一个名为 TestStore.txt 的文件并将“Hello Isolated Storage”写入文件。然后,代码读取该文件并将结果输出到控制台。

 [C#]
using System;
using System.IO;
using System.IO.IsolatedStorage;
 
public class ReadingAndWritingToFiles{
 
   public static int Main(){
 
      // Get an isolated store for this assembly and put it into an
      // IsolatedStoreFile object.
 
      IsolatedStorageFile isoStore =  IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Assembly, null, null);
 
      // This code checks to see if the file already exists.
 
      string[] fileNames = isoStore.GetFileNames("TestStore.txt");
      foreach (string file in fileNames){
         if(file == "TestStore.txt"){
 
            Console.WriteLine("The file already exists!");
            Console.WriteLine("Type \"StoreAdm /REMOVE\" at the command line to delete all Isolated Storage for this user.");
 
            // Exit the program.
 
            return 0;
         }
      }
 
      writeToFile(isoStore);
 
      Console.WriteLine("The file \"TestStore.txt\" contains:");
      // Call the readFromFile and write the returned string to the
      //console.
 
      Console.WriteLine(readFromFile(isoStore));
 
      // Exit the program.
 
      return 0;
 
   }// End of main.
 
 
   // This method writes "Hello Isolated Storage" to the file.
 
   private static void writeToFile(IsolatedStorageFile isoStore){
 
      // Declare a new StreamWriter.
 
      StreamWriter writer = null;
 
      // Assign the writer to the store and the file TestStore.
 
      writer = new StreamWriter(new IsolatedStorageFileStream("TestStore.txt", FileMode.CreateNew,isoStore));
 
      // Have the writer write "Hello Isolated Storage" to the store.
 
      writer.WriteLine("Hello Isolated Storage");
 
      writer.Close();
      
      Console.WriteLine("You have written to the file.");
 
   }// End of writeToFile.
 
 
   // This method reads the first line in the "TestStore.txt" file.
 
   public static String readFromFile(IsolatedStorageFile isoStore){
 
      // This code opens the TestStore.txt file and reads the string.
 
      StreamReader reader = new StreamReader(new IsolatedStorageFileStream("TestStore.txt", FileMode.Open,isoStore));
 
      // Read a line from the file and add it to sb.
 
      String sb = reader.ReadLine();
 
      // Close the reader.
 
      reader.Close();
 
      // Return the string.
 
      return sb.ToString();
 
   }// End of readFromFile.
}

删除文件和目录

您可以删除独立存储文件中的目录和文件。请记住,在存储区中,文件名和目录名是与操作系统相关的(在 Microsoft Windows 系统中通常不区分大小写),并且是根据虚文件系统的根目录具体而定的。
IsolatedStoreFile 类提供了两种删除目录和文件的实例方法:DeleteDirectory 和 DeleteFile。如果尝试删除并不存在的文件和目录,则会引发 IsolatedStorageFileException。如果名称中包含有通配符,则 DeleteDirectory 会引发 IsolatedStorageFileException,而 DeleteFile 将引发 ArgumentException。
如果目录中包含任何文件或子目录,DeleteDirectory 将会失败。在 DeletingFilesAndDirectories 示例的一部分中定义了一个方法,该方法删除目录中的所有内容,然后删除目录本身。同样,您可以自己定义一个接受通配符的 DeleteFiles 方法,该方法可以这样来实现:使用 GetFileNames 方法获取所有匹配文件的列表,然后依次删除每个文件。

DeletingFilesAndDirectories 示例

下面的代码示例先创建若干个目录和文件,然后将它们删除。

 [C#]
using System;
using System.IO.IsolatedStorage;
using System.IO;
 
public class DeletingFilesDirectories{
 
   public static void Main(){
 
      // Get a new isolated store for this user domain and assembly.
      // Put the store into an isolatedStorageFile object.
 
      IsolatedStorageFile isoStore =  IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly, null, null);
    
      Console.WriteLine("Creating Directories:");
 
      // This code creates several different directories.
 
      isoStore.CreateDirectory("TopLevelDirectory");
      Console.WriteLine("TopLevelDirectory");
      isoStore.CreateDirectory("TopLevelDirectory/SecondLevel");
      Console.WriteLine("TopLevelDirectory/SecondLevel");
 
      // This code creates two new directories, one inside the other.
 
      isoStore.CreateDirectory("AnotherTopLevelDirectory/InsideDirectory");
      Console.WriteLine("AnotherTopLevelDirectory/InsideDirectory");
      Console.WriteLine();
 
      // This code creates a few files and places them in the directories.
 
      Console.WriteLine("Creating Files:");
 
      // This file is placed in the root.
 
      IsolatedStorageFileStream isoStream1 = new IsolatedStorageFileStream("InTheRoot.txt", FileMode.Create, isoStore);
      Console.WriteLine("InTheRoot.txt");
  
      isoStream1.Close();
 
      // This file is placed in the InsideDirectory.
 
      IsolatedStorageFileStream isoStream2 = new IsolatedStorageFileStream("AnotherTopLevelDirectory/InsideDirectory/HereIAm.txt", FileMode.Create, isoStore);
      Console.WriteLine("AnotherTopLevelDirectory/InsideDirectory/HereIAm.txt");
      Console.WriteLine();
 
      isoStream2.Close();
 
      Console.WriteLine("Deleting File:");
 
      // This code deletes the HereIAm.txt file.
      isoStore.DeleteFile("AnotherTopLevelDirectory/InsideDirectory/HereIAm.txt");
      Console.WriteLine("AnotherTopLevelDirectory/InsideDirectory/HereIAm.txt"); 
      Console.WriteLine();
 
      Console.WriteLine("Deleting Directory:");
 
      // This code deletes the InsideDirectory.
 
      isoStore.DeleteDirectory("AnotherTopLevelDirectory/InsideDirectory/");
      Console.WriteLine("AnotherTopLevelDirectory/InsideDirectory/");
      Console.WriteLine();
 
   }// End of main.
 
}

总结

    上面是VS.NET中.NET中IO的基本概念、示例代码以及访问文件系统的基础方法和流程,大家可以多多实践。有任何建议请MAIL我 paulni@citiz.net(paulni@citiz.net)。

以上是小编为您精心准备的的内容,在的博客、问答、公众号、人物、课程等栏目也有的相关内容,欢迎继续使用右上角搜索按钮进行搜索目录
, string
, 文件
, console
, The
WriteLine
socketio4net使用、paul jaminet、asp.net 使用html5、netfits.io、netfits.io 2748442,以便于您获取更多的相关知识。

时间: 2024-09-12 04:43:06

使用 .NET的IO(5) Paul的相关文章

使用.NET访问 Internet(1) Paul

Microsoft .NET 框架提供 Internet 服务的分层的.可扩展的和托管的实现,您可以将这些 Internet 服务快速而轻松地集成到您的应用程序中.您的应用程序可建立在可插接式协议的基础之上以便自动利用新的 Internet 协议,或者它们可以使用 Windows 套接字接口的托管实现来使用套接字级别上的网络. 介绍可插接式协议 Microsoft .NET 框架提供分层的.可扩展的和托管的 Internet 服务实现,您可以将它们快速而轻松地集成到您的应用程序中.System.

使用.NET访问 Internet(2) Paul

实现异步请求 System.Net 类使用 .NET 框架的标准异步编程模型对 Internet 资源进行异步访问.WebRequest 类的 BeginGetResponse 和 EndGetResponse 方法分别启动和完成对 Internet 资源的异步请求.注意 在异步回调方法中使用同步调用可能会导致严重的性能降低.通过 WebRequest 及其子代实现的 Internet 请求必须使用 Stream.BeginRead 读取由 WebResponse.GetResponseStre

Red Hat Cormier发布OpenShift.io和容器状态指数

Red Hat为云应用开发人员提供了新功能和针对容器运行状态和安全性的评级服务.同时,它还避免了在本地工作站上使用OpenShift.io来安装开发工具. 近期,数以千计的开发人员参加了在波士顿召开的Red Hat峰会,这些与会的开发人员都是长久以来深入学习应用编程代码和开源技术的获益者.Red Hat公司执行副总裁兼产品与技术业务总裁Paul Cormier接受了SearchCloudApplications的独家采访. 在波士顿召开的2017 Red Hat峰会有超过六千名的与会者参加.您是

PostgreSQL multipolygon 空间索引查询过滤精简优化 - IO,CPU放大优化

标签 PostgreSQL , PostGIS , 空间数据 , 多边形 , bound box , R-Tree , GiST , SP-GiST 背景 在PostgreSQL中,目前对于空间对象的索引,采用的是GiST索引方法,空间树结构如下,每个ENTRY都是一个BOX: 如果对象是多边形,那么在索引结构中,会存储这个多边形的bound box. 那么对于非box类型,一定是会出现空间放大的. 另一方面,如果输入条件是个多边形,那么同样会将这个多边形的BOUND BOX作为输入条件,根据查

分享一个异步任务在遇到IO异常时支持递归回调的辅助方法

public void TryAsyncActionRecursively<TAsyncResult>( string asyncActionName, Func<Task<TAsyncResult>> asyncAction, Action<int> mainAction, Action<TAsyncResult> successAction, Func<string> getContextInfoFunc, Action<E

gitignore.io ------ 一个根据语言,工具或者平台来智能自动生成gitignore文件的在线工具

根据用户输入的语言类型或者平台类型,自动生成对应的gitignore文件. 例如,输入android,eclipse,点击"Genernate"即可. 得到gitignore文件: # Generated by http://gitignore.io ### Android ### # built application files *.apk *.ap_ # files for the dex VM *.dex # Java class files *.class # generat

再谈IO的异步,同步,阻塞和非阻塞

原本转过一个<六种Socket I/O模型幽默讲解>,里面用比喻的方法讲解各种IO,但说到底那个时候我对同步异步这些还是只知其表.还未能完全理解异步和同步,现在觉得清晰一些了.总结一下. 前提概要: IO的过程: 整个IO的过程其实是应用发起IO的请求,到应用获取到IO请求数据的中间过程. 这个中间,其实主要的时间就是系统准备数据的过程.这也是异步技术的优化所在. 对系统调用的理解: 首先,我们要明确一点.IO的操作属于一种系统调用.也就是应用在运行中,进入到内核代码来执行某些重要的操作. 其

asp.net创建文件夹的IO类的问题

C#中.net中得IO类虽然功能很强大,但是正是因为功能强大,所以在很多虚拟服务商的服务器上并不实用 .因为IO.Directory和IO.DirectoryInfo在应用文件夹操作中,会遍历网站所在的硬盘的磁盘跟目录,一般虚拟服务商并不会给这个磁盘的Network service用户开启读取权限,所以在操作文件夹的时候,使用IO下的这两个类会出现如下错误 未找到路径"E:\"的一部分. 说明: 执行当前 Web 请求期间,出现未处理的异常.请检查堆栈跟踪信息,以了解有关该错误以及代码

cgroup介绍、安装和控制cpu,内存,io示例

cgroup介绍         cgroup是control group的简称,它为Linux内核提供了一种任务聚集和划分的机制,通过一组参数集合将一些任务组织成一个或多个子系统.             Cgroups是control groups的缩写,最初由Google工程师提出,后来编进linux内核.         Cgroups是实现IaaS虚拟化(kvm.lxc等),PaaS容器沙箱(Docker等)的资源管理控制部分的底层基础         子系统是根据cgroup对任务的