StreamReader 的用法(C#)

本文提供了一个使用C#进行文件读写的示例代码。通过创建并写入文本到指定路径的文件,然后立即读取该文件的内容并显示在控制台上。此外,还展示了如何使用StreamReader的Read方法来读取单个字符。

using System;
using System.IO;

class Test
{
   
    public static void Main()
    {
        string path = @"c:/temp/MyTest.txt";

        try
        {
            if (File.Exists(path))
            {
                File.Delete(path);
            }

            using (StreamWriter sw = new StreamWriter(path))
            {
                sw.WriteLine("This");
                sw.WriteLine("is some text");
                sw.WriteLine("to test");
                sw.WriteLine("Reading");
            }

            using (StreamReader sr = new StreamReader(path))
            {
                while (sr.Peek() >= 0)
                {
                    Console.Write((char)sr.Read());
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}

 

下面的代码示例演示如何使用 Read()()() 方法重载读取单个字符,并将 ASCII 整数的输出格式设置为十进制和十六进制数。

using System;
using System.IO;

class StrmRdrRead
{
public static void Main()
    {
    //Create a FileInfo instance representing an existing text file.
    FileInfo MyFile=new FileInfo(@"c:/csc.txt");
    //Instantiate a StreamReader to read from the text file.
    StreamReader sr=MyFile.OpenText();
    //Read a single character.
    int FirstChar=sr.Read();
    //Display the ASCII number of the character read in both decimal and hexadecimal format.
    Console.WriteLine("The ASCII number of the first character read is {0:D} in decimal and {1:X} in hexadecimal.",
        FirstChar, FirstChar);
    //
    sr.Close();
    }
}

C# 中,`StreamReader` 主要用于读取文本格式的数据流,例如从文件或网络资源中读取文本内容。然而,如果目标是下载并保存 PDF 文件(二进制文件),使用 `StreamReader` 并不是最佳选择,因为 PDF 是一种二进制格式文件,而不是纯文本。 ### 使用 WebClient 下载 PDF 文件 一个更简单和直接的方法是使用 `WebClient` 类来下载 PDF 文件,并将其保存到本地磁盘: ```csharp using System.Net; string url = "https://example.com/sample.pdf"; string destinationPath = @"C:\path\to\sample.pdf"; using (WebClient client = new WebClient()) { client.DownloadFile(url, destinationPath); } ``` ### 使用 HttpClient 下载 PDF 文件 如果需要更灵活的控制,可以使用 `HttpClient` 来发送请求并获取响应流,然后将流写入本地文件: ```csharp using System.Net.Http; using System.IO; string url = "https://example.com/sample.pdf"; string destinationPath = @"C:\path\to\sample.pdf"; HttpClient client = new HttpClient(); HttpResponseMessage response = await client.GetAsync(url, HttpCompletionOption.ResponseHeadersRead); using (Stream contentStream = await response.Content.ReadAsStreamAsync()) using (FileStream fileStream = new FileStream(destinationPath, FileMode.Create, FileAccess.Write, FileShare.None)) { await contentStream.CopyToAsync(fileStream); } ``` ### 使用 Stream 和 WebRequest 实现下载 如果坚持使用流的方式处理,可以结合 `WebRequest` 和 `WebResponse` 获取远程 PDF 的数据流,并通过 `FileStream` 将其保存为本地文件: ```csharp using System.Net; using System.IO; string url = "https://example.com/sample.pdf"; string destinationPath = @"C:\path\to\sample.pdf"; WebRequest request = WebRequest.Create(url); using (WebResponse response = request.GetResponse()) using (Stream stream = response.GetResponseStream()) using (FileStream fileStream = File.Create(destinationPath)) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0) { fileStream.Write(buffer, 0, bytesRead); } } ``` ### 注意事项 - 如果尝试使用 `StreamReader` 读取 PDF 文件,可能会导致数据损坏,因为它会尝试将字节转换为字符,这并不适用于二进制文件[^1]。 - 在实际应用中,请确保对异常进行适当处理,以应对网络问题或无效的 URL 情况。
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值