StreamReader读取文件保留转义字符致字符串比对失败,求解决方案
问题
使用StreamReader读取TXT文件时,读取的字符串包含多余的双引号,导致后续与Directory.GetFiles()返回的文件路径无法匹配。
读取代码:
using (StreamReader reader = new StreamReader(saveLocation, System.Text.Encoding.UTF8)) { string line; while ((line = reader.ReadLine()) != null) { // 处理逻辑 } }
手动打开文件时,目标行显示为value_start "FILE_NAME",但Visual Studio调试中line变量显示为" value_start \"FILE_NAME\""(注:调试器中的\"是对实际双引号的转义显示,并非字符串实际包含\字符)。
文件写入代码:
private static void WriteIndexFile( string saveLocation, SortedDictionary<string, string> filesToWrite) { using (StreamWriter writer = new StreamWriter(saveLocation, false, System.Text.Encoding.UTF8)) { writer.WriteLine("cross_ref"); foreach (KeyValuePair<string, string> kvp in filesToWrite) { writer.WriteLine($" file_start \"{kvp.Key}\""); writer.WriteLine($" filename \"{kvp.Value}\""); writer.WriteLine($" #modified {File.GetLastWriteTime(kvp.Value).ToString()}"); writer.WriteLine($" file_end"); } writer.WriteLine("end_cross_ref"); } }
读取后的字符串(如"C:data\local\files\file_name.txt")与Directory.GetFiles()返回的路径(如C:data\local\files\file_name.txt)比对不相等,需解决该匹配问题。
解决方案
1. 读取时提取引号内的路径内容
因为写入时故意用双引号包裹了路径,读取后只需去掉这些包裹的引号即可:
方法一:针对固定格式直接处理
如果确定行格式为filename "路径",可以通过字符串截取+Trim去除引号:
using (StreamReader reader = new StreamReader(saveLocation, System.Text.Encoding.UTF8)) { string line; while ((line = reader.ReadLine()) != null) { string trimmedLine = line.TrimStart(); if (trimmedLine.StartsWith("filename ")) { // 去掉前缀后,Trim掉两端的双引号 string filePath = trimmedLine.Substring("filename ".Length).Trim('"'); // 此时filePath可直接与Directory.GetFiles()的结果比对 } } }
方法二:正则表达式提取(适配复杂格式)
如果文件格式可能有变化,用正则匹配双引号内的内容更可靠:
using System.Text.RegularExpressions; // ... using (StreamReader reader = new StreamReader(saveLocation, System.Text.Encoding.UTF8)) { string line; while ((line = reader.ReadLine()) != null) { Match match = Regex.Match(line, @"filename ""(.*?)"""); if (match.Success) { string filePath = match.Groups[1].Value; // 使用filePath进行路径比对 } } }
2. 可选:修改写入逻辑(若无需引号包裹)
如果不需要用双引号区分路径,可以直接修改写入代码,去掉字符串中的双引号:
writer.WriteLine($" file_start {kvp.Key}"); writer.WriteLine($" filename {kvp.Value}");
这种方式读取时直接得到无引号的路径,可直接与Directory.GetFiles()结果匹配,但需确保路径中没有空格等需要引号转义的特殊字符。
内容的提问来源于stack exchange,提问作者SpencePro
相关产品推荐
相关产品推荐

