C# 如何去除掉TXT文件的头尾的空格(不改变其它的格式),然后保存? 如题 解决方案 » 免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货 String的Trim()方法不就是却除掉两端的空格的吗? string strTemp = string.Empty;...... FileStream fs = new FileStream(FilePath, FileMode.OpenOrCreate, FileAccess.Read);StreamReader read = new StreamReader(fs);while (read.Peek() > -1){strTemp = read.ReadLine().Trim();// 去掉所有空格......StreamWriter sw;sw = File.AppendText(FileExportPath);sw.WriteLine(strTemp );sw.Flush();sw.Close();} read.Close(); string str=" a a a a";string str1=str.Trim(); String的Trim()方法不就是却除掉两端的空格的吗是去掉所有的空格如果只需要去掉首尾的,你可以读出来去掉后再写进去 public static void ReplaceSpace() { String fileName = "c:\\forTest.txt"; String[] lines = File.ReadAllLines(fileName); if(lines.Length>0) { lines[0] = lines[0].TrimStart(); lines[lines.Length - 1] = lines[lines.Length - 1].TrimEnd(); } File.WriteAllLines(fileName,lines); }虽然这种效率不高,不过也可以实现,如果是大文件的话,还是用流的方式吧 文件取出的内容Trim()就可以,Trim()会取出头尾的空白符(包括空格、换行符等) string path = "D:\\文件路径.txt"; // 创建文件流 try { StreamReader sr = new StreamReader(path); string content = sr.ReadToEnd().Trim(); StreamWriter sw = new StreamWriter(path + ".txt"); sw.Write(content); sw.Dispose(); sw.Close(); // 关闭流 sr.Dispose(); sr.Close(); // 关闭流 } catch { } 可以改进为对同一个TXT文件,读取一行后,去除两端的空格后,立即更新到该文件的该行吗? string path = "D:\\文件路径.txt"; // 创建文件流 try { StreamReader sr = new StreamReader(path); string content = sr.ReadToEnd().Trim(); StreamWriter sw = new StreamWriter(path); sr.Dispose(); sr.Close(); // 关闭流 sw.Write(content); sw.Dispose(); sw.Close(); // 关闭流 } catch { }OK. 一直想的一个问题,大家来看看 C# gdi+ 清除所绘的图形 请问oracl中如果存储韩文字符串? C#字符串转换 C# 表格 ~问题~ 如何使用Sql语句存储二进制文本?(问题解决后马上结贴) C# 根据开始时间和结束时间计算的问题 窗体的这种效果如何实现,请大家帮帮忙! 有谁知道铁路自助机上运行的软件是用什么工具开发的; 用C#开发的一个小工具,在有的电脑上无法出现界面,任务管理器没有进程,为什么? Socket文件传输问题 关于窗口抢占显示最前面
string strTemp = string.Empty;
......
FileStream fs = new FileStream(FilePath, FileMode.OpenOrCreate, FileAccess.Read);
StreamReader read = new StreamReader(fs);
while (read.Peek() > -1)
{
strTemp = read.ReadLine().Trim();// 去掉所有空格
......
StreamWriter sw;
sw = File.AppendText(FileExportPath);
sw.WriteLine(strTemp );
sw.Flush();
sw.Close();
} read.Close();
string str1=str.Trim();
public static void ReplaceSpace()
{
String fileName = "c:\\forTest.txt";
String[] lines = File.ReadAllLines(fileName);
if(lines.Length>0)
{
lines[0] = lines[0].TrimStart();
lines[lines.Length - 1] = lines[lines.Length - 1].TrimEnd();
}
File.WriteAllLines(fileName,lines);
}虽然这种效率不高,不过也可以实现,如果是大文件的话,还是用流的方式吧
string path = "D:\\文件路径.txt";
// 创建文件流
try
{
StreamReader sr = new StreamReader(path);
string content = sr.ReadToEnd().Trim();
StreamWriter sw = new StreamWriter(path + ".txt");
sw.Write(content);
sw.Dispose();
sw.Close(); // 关闭流
sr.Dispose();
sr.Close(); // 关闭流
}
catch
{
}
string path = "D:\\文件路径.txt";
// 创建文件流
try
{
StreamReader sr = new StreamReader(path);
string content = sr.ReadToEnd().Trim();
StreamWriter sw = new StreamWriter(path);
sr.Dispose();
sr.Close(); // 关闭流 sw.Write(content);
sw.Dispose();
sw.Close(); // 关闭流
}
catch
{
}
OK.