我的文字文件中有雇员电子邮件,如下所示
abc@ewr.com
xyc@df.co.nz
rte@pope.com
ssddsf@fdf.com
我想要改变这样
abc@ewr.com,xyc,df.co.nz,rte@pope.com,ssddsf@fdf.com
如何使用C#代码?
答案 0 :(得分:4)
string yourString = oldString.Replace(' ', ',');
很可能它不是空格而是新线,所以它将是
string yourString = oldString.Replace(Environment.NewLine, ",");
答案 1 :(得分:3)
可以做到这一点;
string linesFromFile = string.Empty;
// Read into string from file
using (StreamReader sr = new StreamReader("filename.txt"))
{
linesFromFile = sr.ReadToEnd();
linesFromFile = linesFromFile.Replace(Environment.NewLine, ",");
Console.WriteLine(linesFromFile);
}
// Write back from string to file
using (StreamWriter sw = new StreamWriter("newFilename.txt"))
{
foreach(string s in linesFromFile.Split(','))
{
sw.WriteLine(s);
}
}
答案 2 :(得分:1)
我会直接对文件进行操作,以避免将潜在巨大的员工数据库读入字符串的开销:
private static void MungeFile(string filename)
{
FileStream fsOut = File.Create(filename+"_out");
FileStream fsIn = File.OpenRead(filename);
StreamReader sr = new StreamReader(fsIn);
StreamWriter sw = new StreamWriter(fsOut);
while (!sr.EndOfStream)
{
string inputLine = sr.ReadLine();
string terminator = (sr.EndOfStream ? "" : ",");
sw.Write(inputLine + terminator);
}
sw.Flush();
fsOut.Close();
}
答案 3 :(得分:0)
Microsoft的文档很好地介绍了这一点: http://msdn.microsoft.com/en-us/library/ms228599.aspx
答案 4 :(得分:0)
将文本文件作为字符串读入,然后执行以下操作以使用逗号替换换行符(如果要替换空格,请将Environment.NewLine替换为''):
String newFile = oldFile.Replace(Environment.NewLine,',');
答案 5 :(得分:0)
这将用','
替换CR \ LF和空格string newContent = string.Join(",",
File.ReadAllLines("sourceFile.txt")
).Replace(' ', ',')
File.WriteAllText("newFile.txt", newContent);