【温故而知新:文件操作】C#的文件读写相关

 

StreamReader类以及其方法ReadLine,Read,ReadToEnd的分析

首先StreamReader类的构造参数非常丰富
在这里,我觉得最常用的就是StreamReader(Stream stream)和StreamReader(String str)这两个最常用
第一个可以直接放入一个数据流,例如FileStream,而第二个更简单直接放入str例如“c:/test.txt”
重点讲的是它的三个方法的使用
1.ReadLine()
当遇到 或者是 的时候 此方法返回这前面的字符串,然后内部的指针往后移一位下次从新的地方开始读
知道遇到数据的结尾处返回null
所以经常这样使用
String content;
try
{
StreamReader sr = new StreamReader("test.txt");
content=sr.ReadLine();
while(null != content)
{
Debug.WriteLine(content);
content=sr.ReadLine();
}
sr.Close();
}
catch(IOException e)
{
Debug.WriteLine(e.ToString());
}

2.Read()
此方法每次读取一个字符,返回的是代表这个字符的一个正数,当独到文件末尾时返回的是-1。
修改上面的使用:

try
{
StreamReader sr = new StreamReader("test.txt");
int content=sr.Read();
while(-1 != content)
{
Debug.Write(Convert.ToChar(content));
content=sr.Read();
}
sr.Close();
}
catch(IOException e)
{
Debug.WriteLine(e.ToString());
}


此处需要补充一点
Read()还有一个使用方法

int Read(char[] buffer,int index,int count);

//补充一下,假设制定每次读128个字符,当文件内容小于128时,它会再循环一遍,从头开始读,直到读够128个字符

从文件流的第index个位置开始读,到count个字符,把它们存到buffer中,然后返回一个正数,内部指针后移一位,保证下次从新的位置开始读。
举个使用的例子:
try
{
StreamReader sr = new StreamReader("test.txt");
char[] buffer=new char[128];
int index=sr.Read(buffer,0,128);
while(index>0)
{
String content = new String(buffer,0,128);
Debug.Write(content);
index=sr.Read(buffer,0,128);
}
sr.Close();
}
catch(IOException e)
{
Debug.WriteLine(e.ToString());
}


3.ReadToEnd()
这个方法适用于小文件的读取,一次性的返回整个文件
上文修改如下:
try
{
StreamReader sr = new StreamReader("test.txt");
String content = sr.ReadToEnd();
Debug.WriteLine();
sr.Close();
}
catch(IOException e)
{
Debug.WriteLine(e.ToString());
}
 
 
 

SharpZipLib 是一个免费的Zip操作类库,可以利用它对 ZIP 等多种格式进行压缩与解压。下载网址:http://www.icsharpcode.net/OpenSource/SharpZipLib/Download.aspx。目前的版本为0.86。
1、创建zip文件,并添加文件:
using (ZipFile zip = ZipFile.Create(@"E: est.zip")) 

    zip.BeginUpdate(); 
    zip.Add(@"E:文件1.txt"); 
    zip.Add(@"E:文件2.txt"); 
    zip.CommitUpdate(); 

 
2、将文件夹压缩为文件
(new FastZip()).CreateZip(@"E: est.zip", @"E: est", true, "");
 
最后一个参数是使用正则表达式表示的过滤文件规则。CreateZip方法有3个重载版本,其中有目录过滤参数、文件过滤参数及用于指定是否进行子目录递归的一个bool类型的参数。
3、将文件添加到已有zip文件中
using (ZipFile zip = new ZipFile(@"E: est.zip"))
{
    zip.BeginUpdate();
    zip.Add(@"E: est.doc");
    zip.CommitUpdate();
}
 
4、列出zip文件中文件
using (ZipFile zip = new ZipFile(@"E: est.zip"))
{
    string list = string.Empty;
    foreach (ZipEntry entry in zip)
    {
        list += entry.Name + " ";
    }
    MessageBox.Show(list);
}
 
5、删除zip文件中的一个文件
using (ZipFile zip = new ZipFile(@"E: est.zip"))
{
    zip.BeginUpdate();
    zip.Delete(@"test.doc");
    zip.Delete(@"test22.txt");
    zip.CommitUpdate();
}
 
 6、解压zip文件中文件到指定目录下
(new FastZip()).ExtractZip(@"E: est.zip", @"E: est", "");
 
7、常用类
ZipInputStream、GZipInputStream用于解压缩Deflate、GZip格式流,ZipOutputStream、GZipOutputStream用于压缩Deflate、GZip格式流。
StreamUtil类包含了几个Stream处理辅助方法:
  1) Copy(Stream, Stream, Byte[])用于从一个Stream对象中复制数据到另一Stream对象。有多个重写。
  2) ReadFully(Stream, Byte [])用于从Stream对象中读取所有的byte数据。有多个重写。

File.WriteAllBytes
http://msdn.microsoft.com/zh-cn/library/system.io.file.writeallbytes.aspx

其他:

这里要注意,byte[]数组里面可能有不可见字符,所以程序里不要进行如GetString()之类的转换,这样会出错的,对一些不可见的字符会有乱码。可以用写二进制流的方式进行读写文件即可。

[csharp] view plain copy
 
    1. FileStream fs1 = new FileStream(@"E: enpdoc111.txt", FileMode.Open, FileAccess.Read, FileShare.Read);  
    2. FileStream fs2 = new FileStream(@"E: empdoc222.txt", FileMode.Create, FileAccess.Write, FileShare.None);  
    3. byte []farr = new byte[1024];  
    4. const int rbuffer=1024;  
    5. //fs1.ReadByte(); //读取单个字节,返回-1表示读完  
    6. while (fs1.Read(farr, 0, rbuffer)!=0) //返回0表示读完  
    7. {  
    8.     fs2.Write(farr, 0, rbuffer);  
    9. }  
    10. fs1.Close();  
    11. fs2.Close();  

C# 大文件的读取处理 
在程序处理的过程中,我们通常读取的文件大小比较小,这样很好处理,
但是如果遇见类似于5G这样的文件,使用常用的读取文件的方法显得就不行了.
这个时候需要将文件进行拆分进行读取.下面是示例代码.
[csharp] view plaincopy

private void BigFileRead(string strFilePath)  
        {  
            //每次读取的字节数  
            int iBufferSize = 1024000;  
            byte[] buffer = new byte[iBufferSize];  
            FileStream fs = null;  
            try  
            {  
                fs = new FileStream(strFilePath, FileMode.Open);  
                //文件流的长度  
                long lFileSize = fs.Length;  
                //文件需要读取次数  
                int iTotalCount = (int)Math.Ceiling((double)(lFileSize / iBufferSize));  
                //当前读取次数  
                int iTempCount = 0;  
  
                while (iTempCount < iTotalCount)  
                {  
                    //每次从最后读到的位置读取下一个[iBufferSize]的字节数  
                    fs.Read(buffer, 0, iBufferSize);  
                    //将字节转换成字符  
                    string strRead = Encoding.Default.GetString(buffer);  
                    //此处加入你的处理逻辑  
                    Console.Write(strRead);  
                }  
            }  
            catch (Exception ex)  
            {  
                //异常处理  
            }  
            finally  
            {  
                if (fs != null)  
                {  
                    fs.Dispose();  
                }  
            }  
        }

本文由机器翻译。若要查看英语原文,请勾选“英语”复选框。 也可将鼠标指针移到文本上,在弹出窗口中显示英语原文。
翻译 英语
File.WriteAllBytes 方法 (String, Byte[])

.NET Framework (current version) 其他版本
 
创建一个新文件,在其中写入指定的字节数组,然后关闭该文件。如果目标文件已存在,则覆盖该文件。
命名空间:   System.IO
程序集:  mscorlib(mscorlib.dll 中)

语法
C#C++F#VB
public static void WriteAllBytes(
string path,
byte[] bytes
)
参数
path
要写入的文件。
bytes
要写入文件的字节。
异常
Exception Condition
ArgumentException
path 是一个零长度字符串,仅包含空白或者包含一个或多个由 InvalidPathChars 定义的无效字符。
ArgumentNullException
path 为 null 或字节数组为空。
PathTooLongException
指定的路径、文件名或者两者都超出了系统定义的最大长度。例如,在基于 Windows 的平台上,路径必须小于 248 个字符,文件名必须小于 260 个字符。
DirectoryNotFoundException
指定的路径无效(例如,它位于未映射的驱动器上)。
IOException
打开文件时发生 I/O 错误。
UnauthorizedAccessException
path 指定了一个只读文件。
- 或 -
当前平台不支持此操作。
- 或 -
path 指定了一个目录。
- 或 -
调用方没有所要求的权限。
NotSupportedException
path 的格式无效。
SecurityException
调用方没有所要求的权限。
备注
给定一个字节数组和文件路径,此方法打开指定的文件、 将字节数组的内容写入该文件,然后关闭该文件。
安全性
FileIOPermission
for access to write to a file or directory.Associated enumeration: FileIOPermissionAccess.Write
版本信息

总结C#获取当前路径的7种方法

推荐方式:

获取网站所运行的程序域

 
以下代码是在查看NOP中看到的 感觉很不错

/// <summary>         /// Gets a physical disk path of Bin directory         /// </summary>         /// <returns>The physical path. E.g. "c:inetpubwwwrootin"</returns>         public virtual string GetBinDirectory()         {             if (HostingEnvironment.IsHosted)             {                 //hosted                 return HttpRuntime.BinDirectory;             }             //not hosted. For example, run either in unit tests             return AppDomain.CurrentDomain.BaseDirectory;         }




 分类:
[csharp] view plain copy
 
 在CODE上查看代码片派生到我的代码片
  1. 总结C#获取当前路径的7种方法  
  2.  C#获取当前路径的方法如下:  
  3. 1. System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName  
  4. -获取模块的完整路径。  
  5. 2. System.Environment.CurrentDirectory  
  6. -获取和设置当前目录(该进程从中启动的目录)的完全限定目录。  
  7. 3. System.IO.Directory.GetCurrentDirectory()  
  8. -获取应用程序的当前工作目录。这个不一定是程序从中启动的目录啊,有可能程序放在C:www里,这个函数有可能返回C:Documents and SettingsYB\,或者C:Program FilesAdobe\,有时不一定返回什么东东,我也搞不懂了。  
  9. 4. System.AppDomain.CurrentDomain.BaseDirectory  
  10. -获取程序的基目录。  
  11. 5. System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase  
  12. -获取和设置包括该应用程序的目录的名称。  
  13. 6. System.Windows.Forms.Application.StartupPath  
  14. -获取启动了应用程序的可执行文件的路径。效果和2、5一样。只是5返回的字符串后面多了一个""而已  
  15. 7. System.Windows.Forms.Application.ExecutablePath  
  16. -获取启动了应用程序的可执行文件的路径及文件名,效果和1一样。  
  17. 对于Windows程序和Web 应用程序来说,他们运行的路径是不一样的,所以关键是判断当前运行的程序是哪种程序.于是我们可以使用如下的代码  
  18. 1   string path = "";    
  19. 2      
  20. 3   if (System.Environment.CurrentDirectory == AppDomain.CurrentDomain.BaseDirectory)//Windows应用程序则相等   
  21. 4      
  22. 5   ...{    
  23. 6      
  24. 7   path = AppDomain.CurrentDomain.BaseDirectory;    
  25. 8      
  26. 9   }    
  27. 10     
  28. 11  else   
  29. 12     
  30. 13  ...{    
  31. 14     
  32. 15  path = AppDomain.CurrentDomain.BaseDirectory + "Bin";    
  33. 16     
  34. 17  }   
  35. 这样如果我们写了一个类库,类库中用到了Assembly.LoadFrom,由于是通用类库,所以可能用到Windows程序中也可能用到Web中,那么用上面的代码就很方便了.  
  36. 1、Server.MapPath  
  37. 2、System.Windows.Forms.StartupPath  
  38. 3、Type.Assembly.Location  
  39. C#获取当前路径方法2可以应用于控制台应用程序,WinForm应用程序,Windows服务,方法1可以应用于Web应用程序,方法3都可以应用。  
  40. 但方法3是加载应用程序的路径。如果是Web应用程序,取得的路径是:C:WINDOWSMicrosoft.NETFrameworkv1.1.4322Temporary ASP.NET Files目录。所以Web项目还是使用Server.MapPath吧。否则建议使用方法2。如果自己新建类库。可以加入对System.Windows.Forms.StartupPath的引用后使用。  
  41. C#获取当前路径的方法就总结到这里,希望对大家有所帮助。  
  42.   
  43.   
  44. C#获取程序当前路径的方法   
  45. //获取新的 Process 组件并将其与当前活动的进程关联的主模块的完整路径,包含文件名(进程名)。  
  46. string str = System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName;  
  47. result: X:xxxxxxxxx.exe (.exe文件所在的目录+.exe文件名)   
  48. //获取和设置当前目录(即该进程从中启动的目录)的完全限定路径。  
  49. string str = System.Environment.CurrentDirectory;  
  50. result: X:xxxxxx (.exe文件所在的目录)  
  51. //获取当前 Thread 的当前应用程序域的基目录,它由程序集冲突解决程序用来探测程序集。  
  52. string str = System.AppDomain.CurrentDomain.BaseDirectory;  
  53. result: X:xxxxxx (.exe文件所在的目录+"")  
  54. //获取和设置包含该应用程序的目录的名称。  
  55. string str = System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase;  
  56. result: X:xxxxxx (.exe文件所在的目录+"")  
  57. //获取启动了应用程序的可执行文件的路径,不包括可执行文件的名称。  
  58. string str = System.Windows.Forms.Application.StartupPath;  
  59. result: X:xxxxxx (.exe文件所在的目录)  
  60. //获取启动了应用程序的可执行文件的路径,包括可执行文件的名称。  
  61. string str = System.Windows.Forms.Application.ExecutablePath;  
  62. result: X:xxxxxxxxx.exe (.exe文件所在的目录+.exe文件名)  
  63. //获取应用程序的当前工作目录(不可靠)。  
  64. string str = System.IO.Directory.GetCurrentDirectory();  
  65. result: X:xxxxxx (.exe文件所在的目录)  
  66.   
  67.   
  68. c# 获取相对路径  
  69.  一、获取当前文件的路径  
  70. 1.   System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName  
  71.      获取模块的完整路径,包括文件名。  
  72. 2.   System.Environment.CurrentDirectory  
  73.      获取和设置当前目录(该进程从中启动的目录)的完全限定目录。  
  74. 3.   System.IO.Directory.GetCurrentDirectory()  
  75.      获取应用程序的当前工作目录。这个不一定是程序从中启动的目录啊,有可能程序放在C:www里,这个函数有可能返回C:Documents and SettingsYB\,或者C:Program FilesAdobe\,有时不一定返回什么东东,这是任何应用程序最后一次操作过的目录,比如你用Word打开了E:docmy.doc这个文件,此时执行这个方法就返回了E:doc了。  
  76. 4. System.AppDomain.CurrentDomain.BaseDirectory  
  77.      获取程序的基目录。  
  78. 5. System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase  
  79.      获取和设置包括该应用程序的目录的名称。  
  80. 6. System.Windows.Forms.Application.StartupPath  
  81.      获取启动了应用程序的可执行文件的路径。效果和2、5一样。只是5返回的字符串后面多了一个""而已  
  82. 7. System.Windows.Forms.Application.ExecutablePath  
  83.      获取启动了应用程序的可执行文件的路径及文件名,效果和1一样。  
  84. 二、操作环境变量  
  85. 利用System.Environment.GetEnvironmentVariable()方法可以很方便地取得系统环境变量,如:  
  86. System.Environment.GetEnvironmentVariable("windir")就可以取得windows系统目录的路径。  
  87. 以下是一些常用的环境变量取值:  
  88. System.Environment.GetEnvironmentVariable("windir");  
  89. System.Environment.GetEnvironmentVariable("INCLUDE");  
  90. System.Environment.GetEnvironmentVariable("TMP");  
  91. System.Environment.GetEnvironmentVariable("TEMP");  
  92. System.Environment.GetEnvironmentVariable("Path");  
  93.  System.Environment.SystemDirectory ;C:/windows/system32目录  
  94. 最后贴出我进行上面操作获得的变量值,事先说明,本人是编写了一个WinForm程序,项目文件存放于D:Visual Studio ProjectsMyApplicationLifeAssistant,编译后的文件位于D:Visual Studio ProjectsMyApplicationLifeAssistantinDebug,最后的结果如下:  
  95. 1、System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName=D:Visual Studio ProjectsMyApplicationLifeAssistantinDebugLifeAssistant.exe  
  96. 2、System.Environment.CurrentDirectory=D:Visual Studio ProjectsMyApplicationLifeAssistantinDebug  
  97. 3、System.IO.Directory.GetCurrentDirectory()=D:Visual Studio ProjectsMyApplicationLifeAssistantinDebug  
  98. 1 asp.net webform用“Request.PhysicalApplicationPath获取站点所在虚拟目录的物理路径,最后包含“”;  
  99. 2.c# winform用  
  100. A:“Application.StartupPath”:获取当前应用程序所在目录的路径,最后不包含“”;  
  101. B:“Application.ExecutablePath ”:获取当前应用程序文件的路径,包含文件的名称;  
  102. C:“AppDomain.CurrentDomain.BaseDirectory”:获取当前应用程序所在目录的路径,最后包含“”;  
  103. D:“System.Threading.Thread.GetDomain().BaseDirectory”:获取当前应用程序所在目录的路径,最后包含“”;  
  104. E:“Environment.CurrentDirectory”:获取当前应用程序的路径,最后不包含“”;  
  105. F:“System.IO.Directory.GetCurrentDirectory”:获取当前应用程序的路径,最后不包含“”;  
  106. 3.c# windows service  
  107. 用“AppDomain.CurrentDomain.BaseDirectory”  
  108. 或“System.Threading.Thread.GetDomain().BaseDirectory”;  
  109. 用“Environment.CurrentDirectory”和  
  110. “System.IO.Directory.GetCurrentDirectory”将得到“ system32”目录的路径;  
  111. 如果要使用“Application.StartupPath”或“Application.ExecutablePath ”,需要手动添加对“System.Windows.Forms.dll ”的引用,并在程序开头用“using System.Windows.Forms”声明该引用;  
  112. 4.在卸载程序获取系统安装的目录:  
  113. System.Reflection.Assembly curPath = System.Reflection.Assembly.GetExecutingAssembly();  
  114.          string path=curPath.Location;//得到安装程序类SetupLibrary文件的路径,获取这个文件路径所在的目录即得到安装程序的目录;  
  115.   
  116. 4、System.AppDomain.CurrentDomain.BaseDirectory=D:Visual Studio ProjectsMyApplicationLifeAssistantinDebug  
  117. 5、System.AppDomain.CurrentDomain.SetupInformation.ApplicationBase=D:Visual Studio ProjectsMyApplicationLifeAssistantinDebug  
  118. 6、System.Windows.Forms.Application.StartupPath=D:Visual Studio ProjectsMyApplicationLifeAssistantinDebug  
  119. 7、System.Windows.Forms.Application.ExecutablePath=D:Visual Studio ProjectsMyApplicationLifeAssistantinDebugLifeAssistant.exe  
  120. System.Environment.GetEnvironmentVariable("windir")=C:WINDOWS  
  121. System.Environment.GetEnvironmentVariable("INCLUDE")=C:Program FilesMicrosoft Visual Studio .NET 2003SDKv1.1include  
  122. System.Environment.GetEnvironmentVariable("TMP")=C:DOCUME~1zhoufoxcnLOCALS~1Temp  
  123. System.Environment.GetEnvironmentVariable("TEMP")=C:DOCUME~1zhoufoxcnLOCALS~1Temp  
  124. System.Environment.GetEnvironmentVariable("Path")=C:WINDOWSsystem32;C:WINDOWS;C:WINDOWSSystem32Wbem;C:jdk1.5.0in;C:MySQLServer5.0in;C:Program FilesSymantecpcAnywhere;C:Program FilesMicrosoft SQL Server80ToolsBINN  
  125.   
  126.   
  127.   
  128.   
  129. C# 相对路径 系统路径  
  130. 2007-12-22 09:53  
  131. //获取启动了应用程序的可执行文件的路径,不包括可执行文件的名称。    
  132. string   str5=Application.StartupPath;  
  133. //可获得当前执行的exe的文件名。        
  134. string   str1   =Process.GetCurrentProcess().MainModule.FileName;  
  135. //获取和设置当前目录(即该进程从中启动的目录)的完全限定路径。备注   按照定义,如果该进程在本地或网络驱动器的根目录中启动,则此属性的值为驱动器名称后跟一个尾部反斜杠(如“C:”)。如果该进程在子目录中启动,则此属性的值为不带尾部反斜杠的驱动器和子目录路径(如“C:mySubDirectory”)。    
  136. string   str2=Environment.CurrentDirectory;  
  137. //获取应用程序的当前工作目录。    
  138. string   str3=Directory.GetCurrentDirectory();  
  139. //获取基目录,它由程序集冲突解决程序用来探测程序集。    
  140. string   str4=AppDomain.CurrentDomain.BaseDirectory;  
  141. //获取启动了应用程序的可执行文件的路径,不包括可执行文件的名称。    
  142. string   str5=Application.StartupPath;  
  143. //获取启动了应用程序的可执行文件的路径,包括可执行文件的名称。    
  144. string   str6=Application.ExecutablePath;  
  145. //获取或设置包含该应用程序的目录的名称。  
  146. string   str7=AppDomain.CurrentDomain.SetupInformation.ApplicationBase;  
  147. //例子  
  148. Application.StartupPath;  
  149. //可以得到F:learningc#TrainingwinwininDebug  
  150. //注意自己补两个  
  151. Application.StartupPath+"\3.jpg";  
  152.    
  153.    
  154.    
  155. 在c#中,相对路径是用"."和".."表示,  
  156. "."代表当前目录,  
  157. ".."代表上一级录。  
  158. 例如 假设我用vs2005在D:My DocumentsVisual Studio 2005Projects目录里创建了一个名叫controls的项目,即在Projects文件夹里有一个controls文件夹,controls文件夹里有三个文件:controls.sln   controls文件夹   GulfOfStLawrence文件夹。  
  159. D:My DocumentsVisual Studio 2005ProjectsControlsControlsinDebug是这个简单项目能够运行的可执行文件Controls.exe  
  160.   
  161. 现在我想要 D:My DocumentsVisual Studio 2005ProjectsControlsGulfOfStLawrence文件夹下的Gulf_of_St._Lawrence.mxd(arcgis desktop)工程文件路径。  
  162. 那么相对路径应该就是"......GulfOfStLawrenceGulf_of_St._Lawrence.mxd"  
  163. string filename = @"......GulfOfStLawrenceGulf_of_St._Lawrence.mxd";  
  164.   
  165. 心得:1.用相对路径能增加项目的可移植性。使一个工程在移植过程中变得简单,节省了大量布置与工程相关的文件的时间。(如果设置的是绝对路径)。  
  166.      2.使用相对路径也使程序代码变得简单  
  167.    3. 但有一点必须注意:(只能在同一个驱动器里(如:都在D:里)使用相对路径)。  
 
 
 
 
原文地址:https://www.cnblogs.com/micro-chen/p/5755765.html