Elahe
Elahe

Reputation: 1399

How to write PNG file in c#

I get the content of my png file by converting this file and I want to write it in my D drive. Its my code :

s = File.ReadAllText(openFileDialog1.FileName.ToString());

File.WriteAllText(@"D:\result.png", s);

but the result is not same with the selected file (.png) and when I write it, it be damaged. I also used ASCII Encoding and UTF, but nothing changed...

any idea? Thanks

Upvotes: 1

Views: 2257

Answers (2)

//Read All Bytes
byte[] fileBytes = File.ReadAllBytes(openFileDialog1.FileName.ToString());

//Data that needs to added, converted to bytes, Better off making a function for this
String str = "Data to be added";
byte[] newBytes = new byte[str.Length * sizeof(char)];
System.Buffer.BlockCopy(str.ToCharArray(), 0, newBytes, 0, newBytes.Length);

//Add the two byte arrays, the file bytes, the new data bytes
byte[] fileBytesWithAddedData = new byte[ fileBytes.Length + newBytes.Length ];
System.Buffer.BlockCopy(fileBytes, 0, fileBytesWithAddedData, 0, fileBytes.Length);
System.Buffer.BlockCopy( newBytes, 0, fileBytesWithAddedData, fileBytes.Length, newBytes.Length );

//Write to new file
File.WriteAllBytes(@"D:\result.png", fileBytesWithAddedData);

Upvotes: 1

CodeCaster
CodeCaster

Reputation: 151740

PNG is binary data, not text. You need to read all bytes and write those.

It does seem though you're just looking for File.Copy.

To read all bytes, use the conveniently named method File.ReadAllBytes() instead.

Upvotes: 3

Related Questions