.NET FileStream文件流,StreamReader文本流,MemoryStream内存流几种流的实例

一、FileStream文件流

1.读取数据

 1    public class ReadFile
 2     {
 3         /// <summary>
 4         /// 读取文件
 5         /// FileMode.Create  创建一个新文件,如果文件已经存在则改写旧文件
 6         /// FileMode.CreateNew 创建一个文件,如果文件存在会发生异常,提示文件已经存在
 7         /// FileMode.Open  打开文件,如果文件不存在则异常
 8         /// FileMode.OpenOrCreate  打开文件,如果文件不存在,则创建一个新的文件并且打开文件
 9         /// FileMode.Append   打开现有文件,并且在现有文件内容后面追加,如果文件不存在则异常
10         /// FileMode.Truncate 根据现有操作系统,截取文件里面的内容,如果文件不存在则异常
11         /// </summary>
12         public static void Read(string FilePath)
13         {
14             FileStream fileStream = null;
15             try
16             {
17               fileStream = new FileStream(FilePath, FileMode.Truncate);
18                 byte[] bytes = new byte[fileStream.Length];
19                 int read = fileStream.Read(bytes, 0, bytes.Length);
20                 var result = Encoding.UTF8.GetString(bytes);
21             }
22             catch (Exception e)
23             {
24                 if (fileStream != null)
25                 {
26                     fileStream.Dispose();
27                 }
28                 Console.WriteLine(e.Message);
29             }
30             finally
31             {
32                 if (fileStream != null)
33                 {
34                     fileStream.Close();
35                     fileStream.Dispose();
36                 }
37             }
38         }
39     }

2.写入数据

 1    public class WriteFile
 2     {
 3         public static void WriteText(string FilePath,string writeString)
 4         {
 5             FileStream fileStream = null;
 6             try
 7             {
 8                 //根据路径打开文件
 9                 fileStream = new FileStream(@"C:\Users\Administrator\source\repos\OperatFile\OperatFile\1.txt", FileMode.Append);
10                 //把字符串转化成字节
11                 byte[] bytes = Encoding.UTF8.GetBytes(writeString);
12                 //写入到文件
13                 fileStream.Write(bytes, 0, bytes.Length);
14             }
15             catch (Exception e)
16             {
17           if (fileStream != null)
18                 {
19                     fileStream.Dispose();
20                 }
21                 Console.WriteLine(e.Message);
22             }
23             finally
24             {
25                 //关闭和释放
26                 if (fileStream != null)
27                 {
28                     fileStream.Close();
29                     fileStream.Dispose();
30                 }
31             }
32         }
33     }

二、StreamReader文本流

1.读取数据

 1    public class SteamReadFile
 2     {
 3         /// <summary>
 4         /// 读取文件
 5         /// </summary>
 6         /// <param name="filePath">文件路径</param>
 7         public static void ReadFile(string FilePath)
 8         {
 9             try
10             {
11                 using (StreamReader sr = new StreamReader(FilePath))
12                 {
13                     var result = sr.ReadToEnd();
14                     Console.WriteLine(result);
15                 }
16             }
17             catch (Exception e)
18             {
19 
20                 throw new Exception(e.Message);
21             }
22         }
23     }

2.写入数据

 1    public class StreamWriteFile
 2     {
 3         /// <summary>
 4         /// 写入文件
 5         /// </summary>
 6         /// <param name="FilePath">文件路径</param>
 7         /// <param name="WriteString">待写入字符串</param>
 8         public static void WriteFile(string FilePath,string WriteString)
 9         {
10             try
11             {
12                 using (StreamWriter sr = new StreamWriter(FilePath))
13                 {
14                     sr.WriteLine(WriteString);
15                 }
16             }
17             catch (Exception e)
18             {
19                 throw new Exception(e.Message);
20             }
21         }
22     }

3.写入日志实例

 1    public class LogHelper
 2     {
 3         /// <summary>
 4         /// 文件路径
 5         /// </summary>
 6         public static string FilePath = @"C:\Users\Administrator\source\repos\OperatFile\OperatFile\Files";
 7         static LogHelper()
 8         {
 9             //判断文件夹是否存在,如果不存在,则重新创建
10             if (!Directory.Exists(FilePath))
11             {
12                 Directory.CreateDirectory(FilePath);
13             }
14         }
15      /// <summary>
16         /// 日志写入
17         /// Path.Combine(str1,str2,str3)  把传入的参数拼接起来,然后返回新的字符串
18         /// File.AppendText(fullPath) 根据文件路径,把新写入的内容,拼接到文本后面
19         /// </summary>
20         public static void WriteLog()
21         {
22             try
23             {
24                 var sb = BindData();
25                 string fullPath = Path.Combine(FilePath, $"{DateTime.Now.ToString("yyyy-MM-dd")}.txt");
26                 //判断文件是否存在,如果不存在,则新建文件
27                 if (!File.Exists(fullPath))
28                 {
29                     File.Create(fullPath);
30                 }
31                 using (StreamWriter sw = File.AppendText(fullPath))
32                 {
33                     sw.WriteLine(sb.ToString());
34                 }
35             }
36             catch (Exception e)
37             {
38                 throw new Exception(e.Message);
39             }
40 
41         }
42      /// <summary>
43         /// 绑定日志信息
44         /// </summary>
45         /// <returns></returns>
46         private static StringBuilder BindData()
47         {
48             StringBuilder sb = new StringBuilder();
49             DateTime operatDateTime = DateTime.Now;
50             string content = "读写文件功能";
51             string operators = "小明";
52             sb.AppendLine($"操作时间:{operatDateTime}");
53             sb.AppendLine($"操作内容:{content}");
54             sb.AppendLine($"操作人:{operators}");
55             sb.AppendLine("------------------------------------------------------------------------------------------");
56             return sb;
57         }
58     }

三、MemoryStream内存流

 1      /// <summary>
 2         /// 根据URL读取内容到内存流
 3         /// </summary>
 4         /// <param name="url"></param>
 5         /// <returns></returns>
 6         public static string DownLoadByUrl(string url)
 7         {
 8             string result = string.Empty;
 9             MemoryStream ms = null;
10             HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
11             HttpWebResponse response = request.GetResponse() as HttpWebResponse;
12             using (var stream = response.GetResponseStream())
13             {
14           byte[] buffer = new byte[response.ContentLength];
15                 int actuallyRead = 0, offset = 0;
16                 do
17                 {
18                     actuallyRead = stream.Read(buffer, offset, buffer.Length - offset);
19                     offset += actuallyRead;
20 
21                 } while (actuallyRead > 0);
22                 ms = new MemoryStream(buffer);
23                 ms.Seek(0, SeekOrigin.Begin);
24                 var byteArray = new byte[ms.Length];
25                 ms.Read(byteArray, 0, byteArray.Length);
26                 result = Encoding.UTF8.GetString(byteArray);
27             }
28             response.Close();
29             response.Dispose();
30             return result;
31         }

 

posted @ 2019-06-18 09:47  字里行间  阅读(1358)  评论(0编辑  收藏  举报