Click here to Skip to main content
15,897,704 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi..
how to convert data string to byte[]. i doing downloading file in c#. but i got an error cannot implicit convert type 'string' to 'byte[]' how can i solve this problem...

this is my sample coding
C#
string filename = filename;

           Byte[] bytes = attachment;
           try
           {
               Response.Clear();
               Response.AddHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
               Response.AddHeader("Content-Length", bytes.Length.ToString());
               Response.ContentType = "application/octet-stream";
               Response.BinaryWrite(bytes);
               Response.Flush();
           }
           catch (Exception ex)
           {
               Response.ContentType = "text/plain";
               Response.Write(ex.Message);
           }
           finally
           {
               Response.End();
           }

i got an error at Byte[] bytes = attachment


Thanks in advance
Posted
Updated 9-Feb-13 2:10am
v5

string to byte[]:
C#
string s = ...
byte[] bytes = System.Text.Encoding.ASCII.GetBytes(s);
Depending on what your file was written with, you may want to use one of the other Encoding options instead of ASCII. Unicode, UTF7 or UTF8 perhaps.
 
Share this answer
 
Hi,

Use the Encoding.GetBytes Method[^]
C#
byte[] array = Encoding.yourEncoding.GetBytes(stringData);

Change yourEncoding into the encoding you want to use.
For example:
C#
byte[] array = Encoding.UTF8.GetBytes(stringData);


Another way:

C#
byte[] array = Encoding.GetEncoding("encodingName").GetBytes(stringData);

For example:
C#
byte[] array = Encoding.GetEncoding("utf-32").GetBytes(stringData);

Hope this helps.
 
Share this answer
 
write
byte[] bytes = attachment;
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900