2016-02-05 39 views
0

我通過將文件中的行結尾從DOS轉換爲UNIX格式的C#文件中刪除了Carriage return。這基本上意味着我正在刪除文件格式的回車符。在Windows中創建一個tar歸檔文件重新引入了CR字符

的代碼我使用:

private void Dos2Unix(string fileName) 
{ 
    const byte CR = 0x0D; 
    const byte LF = 0x0A; 
    byte[] data = File.ReadAllBytes(fileName); 
    using (FileStream fileStream = File.OpenWrite(fileName)) 
    { 
     BinaryWriter bw = new BinaryWriter(fileStream); 
     int position = 0; 
     int index = 0; 
     do 
     { 
      index = Array.IndexOf<byte>(data, CR, position); 
      if ((index >= 0) && (data[index + 1] == LF)) 
      { 
       // Write before the CR 
       bw.Write(data, position, index - position); 
       // from LF 
       position = index + 1; 
      } 
     } 
     while (index > 0); 
     bw.Write(data, position, data.Length - position); 
     fileStream.SetLength(fileStream.Position); 
    } 
} 

但經過我轉換,從DOS到Unix的格式,我需要創建所有轉換後的文件的一個tar歸檔。當我使用此代碼創建文件的tar歸檔文件時:

batchFileContents[1] = String.Format("\"C:\\Program Files (x86)\\7-Zip\\7z.exe\" a -ttar -so archive.tar \"{0}\"* | " + 
         "\"C:\\Program Files (x86)\\7-Zip\\7z.exe\" a -si \"{1}\"", inputDirectory, nameOfFile); 

File.WriteAllLines("execute.bat", batchFileContents); 

回車符將在所有文件中重新出現。

上面的dos2unix函數能夠去掉回車符。但問題是,當tar創建存檔時,回車再次出現。如何避免這一點?

我該如何解決這個問題?需要一些指導。

+0

我建議安裝cygwin並使用** dos2unix **刪除回車符,** tar **創建歸檔文件。 – Rumbleweed

+0

dos2unix函數能夠刪除回車符。但問題是,當tar創建存檔時,回車再次出現。如何避免這一點。 – lakesh

+0

Tar不會修改文件。 7z是你的罪魁禍首。 – Rumbleweed

回答

0

爲什麼使用7zip創建tar檔案?最終,你無法控制第三方程序的行爲。

你可以試試https://code.google.com/archive/p/tar-cs/這是一個庫,直接從C#創建tar檔案,它是開源的。如果最後添加回車符,您可以嘗試其他庫或查看自己的源代碼以查看原因。

+0

但我的問題是當我在窗口中執行tar時,它仍會添加回車符。如何避免這種情況? – lakesh

+0

回車不只是自動添加,有的東西必須放在那裏後,你已經刪除它。您使用'7z.exe'來創建tar檔案,我所說的是使用別的東西來創建tar檔案,在這種情況下可能不會像7zip那樣添加回車符。 – caesay

0

首先,避免重複的(方形)輪:

現在,the tar format根據定義,只是使用最小的元數據粘在一起的文件。沒有涉及數據轉換。所以,你的問題在別處 - 也許你正在歸檔錯誤的文件或檢查存檔數據的不忠實表示。

相關問題