vs報錯“以下文件中的行尾不一致,是否將行尾標准化”
分析:
通過讀取源文件,發現換行都使用的是“\n”
Windows和Unix不同的標准引起的...即“回車”和“換行”的問題...
符號 | ASCII碼 | 意義 |
\n | 10 | 換行NL |
\r | 13 | 回車CR |
在計算機還沒有出現之前,有一種叫做電傳打字機(Teletype Model 33)的玩意,每秒鍾可以打10個字符。但是它有一個問題,就是打完一行換行的時候,要用去0.2秒,正好可以打兩個字符。要是在這0.2秒里面,又有新的字符傳過來,那么這個字符將丟失。於是,研制人員想了個辦法解決這個問題,就是在每行后面加兩個表示結束的字符。一個叫做“回車”,告訴打字機把打印頭定位在左邊界;另一個叫做“換行”,告訴打字機把紙向下移一行。到了GUI時代光標都是自由移動的不再有回車的意義...
所以符合Windows開發標准的文本編輯器Visual Studio才會提醒你當前編輯的文本不符合Windows行尾標准..
1.Windows 中的換行符"\r\n"
2.Unix/Linux 平台換行符是 "\n"。
3.MessageBox.Show() 的換行符為 "\n"
4.Console 的換行符為 "\n"
換行符還因平台差異而不同。
解決方案:
1. 為保持平台的通用性,可以用系統默認換行符 System.Environment.NewLine。
2. 替換所有的非標准換行符

1 class Program_Utf8 2 { 3 static void Main(string[] args) 4 { 5 String folderPath = @"E:\文件夾路徑\"; 6 7 ParseDirectory(folderPath, "*.cs", (filePath) => 8 { 9 string text = ""; 10 using (StreamReader read = new StreamReader(filePath, Encoding.Default)) 11 { 12 string oldtext = read.ReadToEnd(); 13 text = oldtext; 14 text = text.Replace("\n", "\r\n"); 15 text = text.Replace("\r\r\n", "\r\n"); // 防止替換了正常的換行符 16 if (oldtext.Length == text.Length) 17 { 18 Console.WriteLine(filePath.Substring(filePath.LastIndexOf("\\") + 1) + " 不需要標准化"); 19 return; // 如果沒有變化就退出 20 } 21 } 22 File.WriteAllText(filePath, text, Encoding.UTF8); //utf-8格式保存,防止亂碼 23 24 Console.WriteLine(filePath.Substring(filePath.LastIndexOf("\\") + 1) + " 行尾標准化完成"); 25 }); 26 27 Console.ReadKey(); 28 } 29 30 /// <summary>遞歸所有的目錄,根據過濾器找到文件,並使用委托來統一處理</summary> 31 /// <param name="info"></param> 32 /// <param name="filter"></param> 33 /// <param name="action"></param> 34 static void ParseDirectory(string folderPath, string filter, Action<string> action) 35 { 36 if (string.IsNullOrWhiteSpace(folderPath) 37 || folderPath.EndsWith("debug", StringComparison.OrdinalIgnoreCase) 38 || folderPath.EndsWith("obj", StringComparison.OrdinalIgnoreCase) 39 || folderPath.EndsWith("bin", StringComparison.OrdinalIgnoreCase)) 40 return; 41 42 Console.WriteLine("讀取目錄:" + folderPath); 43 44 // 處理文件 45 string[] fileNameArray = Directory.GetFiles(folderPath, filter); 46 if (fileNameArray.Length > 0) 47 { 48 foreach (var filePath in fileNameArray) 49 { 50 action(filePath); 51 } 52 } 53 else 54 { 55 Console.WriteLine("未發現文件!"); 56 } 57 58 Console.WriteLine("===================================="); 59 60 //得到子目錄,遞歸處理 61 string[] dirs = Directory.GetDirectories(folderPath); 62 var iter = dirs.GetEnumerator(); 63 while (iter.MoveNext()) 64 { 65 string str = (string)(iter.Current); 66 ParseDirectory(str, filter, action); 67 } 68 } 69 }