2013-08-19 56 views
3

我有一些C++代碼,通過STL字符串將字節值保存到文件中&文本I/O,並且對如何在C#中執行此操作感到困惑。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 (*) 
    } 

你如何做這些任務(*)?

+0

[.NET String to byte Array C#]的可能重複(http://stackoverflow.com/questions/472906/net-string-to-byte-array-c-sharp) – TGO

+1

有點含糊......你想獲得這些字節的文本表示? IE:'byte [] {0,1,2,3}'變成'「0 1 2 3」'? – Corey

回答

4

Encoding支持你所需要的,下面的例子假設你需要使用UTF8,反之亦然,以string轉換爲byte[]

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

如果您需要使用其他的編碼,就可以很容易地改變:

Encoding.Unicode 
Encoding.ASCII 
... 
+2

值得注意的是'System.String'將它的數據作爲「基本格式」存儲在'UTF-16'中。您可以使用正確的'Encoding'將該格式轉換爲任何其他格式的字節,正如您在答案中所演示的那樣。 :] – TheBuzzSaw

0

這個已經回答了一遍又一遍

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); 
} 


How do I get a consistent byte representation of strings in C# without manually specifying an encoding?

仔細閱讀第一個答案,爲什麼你寧願給編碼版本的原因。

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; } 



} 
0

您可以使用此代碼從字符串數組轉換爲字節和ViseVersa

點擊鏈接瞭解更多有關C# byte array to string, and vice-versa

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); 
} 

我希望這可以幫助你。謝謝。

相關問題