如何用StreamReader读取C#字符串?现有代码问题求助
用StreamReader读取C#预设字符串的解决方案
你遇到的问题是直接输出StreamReader对象导致打印类型名,且未正确将字符串转换为流供StreamReader读取。以下是具体实现方法:
核心思路
StreamReader需要读取流对象而非直接读取字符串,因此要先把预设字符串转换为内存流(MemoryStream),再用StreamReader读取内容,最后解析成数值。
示例代码(单一行带分隔符的字符串)
假设你的预设字符串是用逗号分隔的价格:
using System; using System.IO; using System.Text; class Program { static void Main() { // 预设的字符串输入 string itemCostsInput = "10.5,20.3,15,7.8"; // 将字符串转换为字节数组,再包装成内存流 byte[] stringBytes = Encoding.UTF8.GetBytes(itemCostsInput); using (MemoryStream memoryStream = new MemoryStream(stringBytes)) using (StreamReader reader = new StreamReader(memoryStream)) { // 读取流中的全部内容 string fullContent = reader.ReadToEnd(); // 分割字符串并转换为数值类型(这里用decimal适配价格场景) string[] costParts = fullContent.Split(','); decimal[] itemCosts = Array.ConvertAll(costParts, part => decimal.Parse(part)); // 输出验证结果 foreach (decimal cost in itemCosts) { Console.WriteLine($"商品价格:{cost}"); } } } }
多行字符串的处理方式
如果预设字符串是多行格式,可使用ReadLine()逐行读取:
using System; using System.IO; using System.Text; class Program { static void Main() { string itemCostsInput = "10.5\n20.3\n15\n7.8"; using (MemoryStream memoryStream = new MemoryStream(Encoding.UTF8.GetBytes(itemCostsInput))) using (StreamReader reader = new StreamReader(memoryStream)) { string line; // 逐行读取直到流结束 while ((line = reader.ReadLine()) != null) { // 用TryParse避免格式错误导致崩溃 if (decimal.TryParse(line, out decimal cost)) { Console.WriteLine($"商品价格:{cost}"); } } } } }
关键注意点
- 必须用
MemoryStream将字符串转换为流,StreamReader无法直接读取字符串。 - 直接输出StreamReader对象会打印其类型名(
System.IO.StreamReader),需调用ReadToEnd()或ReadLine()获取内容。 - 用
using语句包裹流和StreamReader,自动释放资源,避免内存泄漏。 - 转换数值时优先使用
TryParse,防止输入格式错误引发异常。
内容的提问来源于stack exchange,提问作者조양훈
相关产品推荐
相关产品推荐

