7

我有一些 C++ 代码通过 STL 字符串和文本 i/o 将字节值保存到文件中,并且对如何在 C# 中执行此操作感到困惑。

首先,我将字节数组转换为字符串并将每个数组作为一行存储在文本文件中:

 StreamWriter F
 loop
 {
   byte[] B;       // array of byte values from 0-255 (but never LF,CR or EOF)
   string S = B;   // I'd like to do this assignment in C# (encoding? ugh.) (*)
   F.WriteLine(S); // and store the byte values into a text file
 }

稍后...我想颠倒这些步骤并取回原始字节值:

  StreamReader F;   
  loop
  {
    string S = F.ReadLine();   // read that line back from the file
    byte[] B = S;              // I'd like to convert back to byte array (*)
  }

你是怎么做这些作业的(*)?

4

4 回答 4

9

Encoding支持您需要的内容,下面的示例假设您需要转换stringbyte[]using UTF8,反之亦然:

string S = Encoding.UTF8.GetString(B);
byte[] B = Encoding.UTF8.GetBytes(S);

如果您需要使用其他编码,您可以轻松更改:

Encoding.Unicode
Encoding.ASCII
...
于 2013-08-19T03:47:55.490 回答
1

这个已经被回答了一遍又一遍

static byte[] GetBytes(string str)
{
    byte[] bytes = new byte[str.Length * sizeof(char)];
    System.Buffer.BlockCopy(str.ToCharArray(), 0, bytes, 0, bytes.Length);
    return bytes;
}

static string GetString(byte[] bytes)
{
    char[] chars = new char[bytes.Length / sizeof(char)];
    System.Buffer.BlockCopy(bytes, 0, chars, 0, bytes.Length);
    return new string(chars);
}


如何在不手动指定编码的情况下获得 C# 中字符串的一致字节表示?

仔细阅读第一个答案,以及为什么你更喜欢这个编码版本的原因。

于 2013-08-19T03:50:38.003 回答
0

您可以使用此代码从字符串数组转换为字节和 ViseVersa

单击链接以了解有关C# 字节数组到字符串的更多信息,反之亦然

string strText = "SomeTestData";

            //CONVERT STRING TO BYTE ARRAY
            byte[] bytedata = ConvertStringToByte(strText);                              

            //VICE VERSA ** Byte[] To Text **
            if (bytedata  != null)
            {                    
                //BYTE ARRAY TO STRING
                string strPdfText = ConvertByteArrayToString(result);
            }


//Method to Convert Byte[] to string
private static string ConvertByteArrayToString(Byte[] ByteOutput)
{
            string StringOutput = System.Text.Encoding.UTF8.GetString(ByteOutput);
            return StringOutput;
}


//Method to Convert String to Byte[]
public static byte[] ConvertStringToByte(string Input)
{
            return System.Text.Encoding.UTF8.GetBytes(Input);
}

我希望这可以帮助你。谢谢。

于 2015-04-24T09:45:19.120 回答
0
    public Document FileToByteArray(string _FileName)
    {
        byte[] _Buffer = null;

        try
        {
            // Open file for reading
         FileStream _FileStream = new FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
            // attach filestream to binary reader
           BinaryReader _BinaryReader = new BinaryReader(_FileStream);
            // get total byte length of the file
            long _TotalBytes = new FileInfo(_FileName).Length;
            // read entire file into buffer
            _Buffer = _BinaryReader.ReadBytes((Int32)_TotalBytes);
            // close file reader
            _FileStream.Close();
            _FileStream.Dispose();
            _BinaryReader.Close();
            Document1 = new Document();
            Document1.DocName = _FileName;
            Document1.DocContent = _Buffer;
            return Document1;
        }
        catch (Exception _Exception)
        {
            // Error
            Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
        }

        return Document1;
    }

    public void ByteArraytoFile(string _FileName, byte[] _Buffer)
    {
        if (_FileName != null && _FileName.Length > 0 && _Buffer != null)
        {
            if (!Directory.Exists(Path.GetDirectoryName(_FileName)))
                Directory.CreateDirectory(Path.GetDirectoryName(_FileName));

            FileStream file = File.Create(_FileName);

            file.Write(_Buffer, 0, _Buffer.Length);

            file.Close();
        }



    }

public static void Main(string[] args)
    {
        Document doc = new Document();
        doc.FileToByteArray("Path to your file");
        doc.Document1.ByteArraytoFile("path to ..to be created file", doc.Document1.DocContent);
    }
private Document _document;

public Document Document1
{
    get { return _document; }
    set { _document = value; }
}
public int DocId { get; set; }
public string DocName { get; set; }
public byte[] DocContent { get; set; }



}
于 2014-07-03T07:04:16.977 回答