将node.js脚本转换为c#



我在Node.js中有这个函数

let inPath = process.argv[2] || 'file.txt';
let outPath = process.argv[3] || 'result.txt';
fs.open(inPath, 'r', (errIn, fdIn) => {
fs.open(outPath, 'w', (errOut, fdOut) => {
let buffer = Buffer.alloc(1);
while (true) {
let num = fs.readSync(fdIn, buffer, 0, 1, null);
if (num === 0) break;
fs.writeSync(fdOut, Buffer.from([255-buffer[0]]), 0, 1, null);
}
});
});

在c#中等效的是什么?

我的代码到目前为止。我不知道c#中减去字符字节的等效代码是什么。提前谢谢你!

var inPath = "file.txt";
var outPath = "result.txt";
string result = string.Empty;
using (StreamReader file = new StreamReader(@inPath))
{
while (!file.EndOfStream)
{
string line = file.ReadLine();
foreach (char letter in line)
{
//letter = Buffer.from([255-buffer[0]]);
result += letter;
}
}
File.WriteAllText(outPath, result);
}
var inPath = "file.txt";
var outPath = "result.txt";
//Converted
using (var fdIn = new FileStream(inPath,FileMode.Open))
{
using (var fdOut = new FileStream(outPath, FileMode.OpenOrCreate))
{
var buffer = new byte[1];
var readCount = 0;
while (true)
{
readCount += fdIn.Read(buffer,0,1);
buffer[0] = (byte)(255 - buffer[0]);
fdOut.Write(buffer);
if (readCount == fdIn.Length) 
break;
}
}
}
...
//Same code but all file loaded into memory, processed and after this saved
var input = File.ReadAllBytes(inPath);
for (int i = 0; i < input.Length; i++)
{
input[i] = (byte)(255 - input[i]);
}
File.WriteAllBytes(outPath, input);

相同的代码,但使用了BinaryReader和BinaryWriter

var inPath = "file.txt";
var outPath = "result.txt";
using (BinaryReader fileIn = new BinaryReader(new StreamReader(@inPath).BaseStream))
using (BinaryWriter fileOut = new BinaryWriter(new StreamWriter(@outPath).BaseStream))
{
while (fileIn.BaseStream.Position != fileIn.BaseStream.Length)
{
var @byte = fileIn.ReadByte();
fileOut.Write((byte)(255 - @byte));
}
}

最新更新