我通过将文件中的行结尾从DOS转换为UNIX格式的C#来删除文件中的回车符。这基本上意味着我将以文件格式删除回车符。
我使用的代码:
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 :(得分:0)
为什么要使用7zip创建tar存档?最终,您无法控制第三方程序的行为。
您可以尝试https://code.google.com/archive/p/tar-cs/这是一个库来直接从C#创建tar档案,它是开源的。如果最终添加回车符,您可以尝试使用另一个库或查看自己的源以查看原因。
答案 1 :(得分:0)
首先,避免重新发明(方形)轮:
d2u
实用程序(如果您不想打扰Cygwin,可以获取其源代码并重新编译或Windows端口)。您选择在.NET does appear to be optimal for medium-sized files中执行此操作的方式。system()
库函数,a typical crutch is to prepend them with cmd /c
)。现在,根据定义,the tar
format只是用最少的元数据粘在一起的文件。没有涉及数据转换。所以,你的问题出在其他地方 - 也许你正在存档错误的文件或检查存档数据的不忠实表示。