如何在 C# 中将 Integer 写入 FileStream?
How can I write a Integer to a FileStream in C#?
我想知道是否有人可以帮助我解决 运行 在使用 FileStreams 时遇到的问题。我一直在尝试将整数 50 发送到 FileStream 并将其值写入文件。但是,它将 2 而不是 50 写入文件。我知道 50 的 ASCII 表示形式是 2,所以我不确定这是否是问题的一部分。如果有人有任何指点,我将不胜感激!
这是我的相关代码:
来自主要功能:
string testMessage = "Testing writing some arbitrary string to a streama";
int tmL = testMessage.Length;
byte bb = Convert.ToByte(tmL);
SendByteStrem(bb);
这是我的流媒体功能:
public static void SendByteStrem(byte c){
using (Stream ioStream = new FileStream(@"C:\Users\db0201\Desktop\stream.txt", FileMode.OpenOrCreate)){
ioStream.WriteByte(c);
}
}
由于您没有明确说明您的目标,我将回答您的问题。
写入文件的最简单方法是使用 File.WriteAllText
which essentially opens a StreamWriter
(which in-turn is open a FileStream
) and calls Write
Creates a new file, write the contents to the file, and then closes
the file. If the target file already exists, it is overwritten.
File.WriteAllText(fileName, "50")
或
var myInt = 50;
File.WriteAllText(fileName, myInt.ToString())
如果您想专门使用 StreaWriter
using (varwriter = new StreamWriter(fileName))
writer.Write(myInt.ToString());
如果你想在基础上进行更多配置 FileStream
using (var writer = new StreamWriter(new FileStream(fileName, FileMode.CreateNew)))
writer.Write(myInt.ToString());
如果你只想使用 FileStream
那么事情会变得更加手动,因为你需要将东西转换为 bytes
using (var stream = new FileStream(fileName, FileMode.CreateNew))
{
var bytes = Encoding.UTF8.GetBytes(myInt.ToString());
stream.Write(bytes, 0, bytes.Length);
}
我想知道是否有人可以帮助我解决 运行 在使用 FileStreams 时遇到的问题。我一直在尝试将整数 50 发送到 FileStream 并将其值写入文件。但是,它将 2 而不是 50 写入文件。我知道 50 的 ASCII 表示形式是 2,所以我不确定这是否是问题的一部分。如果有人有任何指点,我将不胜感激!
这是我的相关代码: 来自主要功能:
string testMessage = "Testing writing some arbitrary string to a streama";
int tmL = testMessage.Length;
byte bb = Convert.ToByte(tmL);
SendByteStrem(bb);
这是我的流媒体功能:
public static void SendByteStrem(byte c){
using (Stream ioStream = new FileStream(@"C:\Users\db0201\Desktop\stream.txt", FileMode.OpenOrCreate)){
ioStream.WriteByte(c);
}
}
由于您没有明确说明您的目标,我将回答您的问题。
写入文件的最简单方法是使用 File.WriteAllText
which essentially opens a StreamWriter
(which in-turn is open a FileStream
) and calls Write
Creates a new file, write the contents to the file, and then closes the file. If the target file already exists, it is overwritten.
File.WriteAllText(fileName, "50")
或
var myInt = 50;
File.WriteAllText(fileName, myInt.ToString())
如果您想专门使用 StreaWriter
using (varwriter = new StreamWriter(fileName))
writer.Write(myInt.ToString());
如果你想在基础上进行更多配置 FileStream
using (var writer = new StreamWriter(new FileStream(fileName, FileMode.CreateNew)))
writer.Write(myInt.ToString());
如果你只想使用 FileStream
那么事情会变得更加手动,因为你需要将东西转换为 bytes
using (var stream = new FileStream(fileName, FileMode.CreateNew))
{
var bytes = Encoding.UTF8.GetBytes(myInt.ToString());
stream.Write(bytes, 0, bytes.Length);
}