convert binary file to text

末鹿安然 提交于 2020-03-25 03:21:29

问题


I have a program that gets a response from a url in binary format and I do not know how to convert this to a text file.

byte[] postBytes = System.Text.Encoding.UTF8.GetBytes(postString);
request.ContentLength = postBytes.Length;
Stream stream = request.GetRequestStream();
stream.Write(postBytes, 0, postBytes.Length);
stream.Close();

response = (HttpWebResponse)request.GetResponse();
Stream ReceiveStream = response.GetResponseStream();
string filename = "C:\\responseGot.txt";

byte[] buffer = new byte[1024];
FileStream outFile = new FileStream(filename, FileMode.Create);
int bytesRead;
while ((bytesRead = ReceiveStream.Read(buffer, 0, buffer.Length)) != 0) 
    outFile.Write(buffer, 0, bytesRead);

When I open responseGot.txt it is a binary file how do I get text file.


回答1:


In what format is the response you get? There is no such thing as a text file. There are only binary files. HTTP is also 100% binary.

Text is the interpretation of bytes, and it only exists as part of running application. You can never, ever write text to a file. You can only convert the text to bytes (using various ways) and write the bytes.

Therefore, ask yourself why the bytes you received cannot be interpreted by notepad.exe as text. Maybe the response is not directly text but a ZIP file or something.

  1. You can guess the format with a hex editor
  2. You can ask the website owner



回答2:


You don't show in your code sample saving the file anywhere.

But to convert the response to string you can use:

   using (HttpWebResponse response = req.GetResponse() as HttpWebResponse)   
    {  
      StreamReader reader = new StreamReader(response.GetResponseStream());
      string ResponseTXT = reader.ReadToEnd();
    }

Then you can save it with usual techniques http://msdn.microsoft.com/en-us/library/6ka1wd3w%28v=vs.110%29.aspx

Did you mean that?




回答3:


Use the ReadFully method in this topic Creating a byte array from a stream

Get the string representation to an actual string:

string text = System.Text.Encoding.Default.GetString(byteArray);

And finally create the text file and write the content:

using(StreamWriter sw = new StreamWriter("C:\\responseGot.txt"))
{
        sw.WriteLine(text);
}


来源:https://stackoverflow.com/questions/20422257/convert-binary-file-to-text

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!