5

I am trying to convert a binary data to its original format ".PDF," but either of the solutions I have braek my hed. The first is a little one, it creates a PDF file but it appears empty. The second one also creates a PDF file, but I can't open it. Where is the error?

First code:

Conn.Open();
SqlCommand cmd = Conn.CreateCommand();
cmd.CommandText = "Select Artigo From Artigo WHERE (IDArtigo ='" + id + "')";
byte[] binaryData = (byte[])cmd.ExecuteScalar();

string s = Encoding.UTF8.GetString(binaryData);

File.WriteAllText("algo.pdf", s);

Second code:

Conn.Open();
SqlCommand cmd = Conn.CreateCommand();
cmd.CommandText = "Select Artigo From Artigo WHERE (IDArtigo ='" + id + "')";
byte[] binaryData = (byte[])cmd.ExecuteScalar();

// Convert the binary input into Base64 UUEncoded output.
string base64String;
try
{
    base64String = System.Convert.ToBase64String(binaryData, 0, binaryData.Length);
}
catch (System.ArgumentNullException)
{
    MessageBox.Show("Binary data array is null.");
    return;
}

cmd.CommandText = "Select Titulo From Artigo WHERE (IDArtigo ='" + id + "')";
string titulo = (string)cmd.ExecuteScalar();

// Write the UUEncoded version to the output file.
System.IO.StreamWriter outFile;
try
{
    outFile = new StreamWriter(titulo + ".pdf", false, System.Text.Encoding.ASCII);
    outFile.Write(base64String);
    outFile.Close();
}
catch (System.Exception exp)
{
    System.Console.WriteLine("{0}", exp.Message);
}
GSerg
  • 76,472
  • 17
  • 159
  • 346
Mario_PT
  • 103
  • 2
  • 3
  • 9
  • You can look at [this](http://stackoverflow.com/questions/3961804/itextsharp-creation-of-a-pdf-from-a-list-of-byte-arrays) if you want to create PDF from byte array. – Tilak Jan 01 '13 at 15:01

3 Answers3

10

You are writing the file as text, but you should be writing the raw bytes. A .PDF file is a binary file, not a text file, so in effect, you're filling it with the wrong data in your first code sample.

Try

    Conn.Open();
    SqlCommand cmd = Conn.CreateCommand();
    cmd.CommandText = "Select Artigo From Artigo WHERE (IDArtigo = @id)";
    cmd.Parameters.AddWithValue("@id", id);
    byte[] binaryData = (byte[])cmd.ExecuteScalar();
    File.WriteAllBytes(("algo.pdf", binaryData);
    string s = Encoding.UTF8.GetString(binaryData);

System.IO.File.WriteAllBytes is documented at http://msdn.microsoft.com/en-us/library/system.io.file.writeallbytes.aspx if you have more questions.

Mathias
  • 1,819
  • 4
  • 22
  • 34
David
  • 72,686
  • 18
  • 132
  • 173
  • 2
    This is the best answer I have found across multiple questions and searches. I would just like to suggest parameterizing this command text, instead of concatenating a string. Even if your id variable is set up as an int and you're not concerned about security it's still a good habit for consistency's sake. – Brad Oct 14 '16 at 13:30
3

Try File.WriteAllBytes with the original data (binaryData) and do not try to convert it to anything else

CubeSchrauber
  • 1,199
  • 8
  • 9
0
string sql = "select Lsn_File from Lessons_tbl where Lsn_name = '"TextBox1.Text + "'";

        cmd = new SqlCommand(sql, dal.cn());

        dal.Open();
        SqlDataReader dr = cmd.ExecuteReader();

         dr.Read();
         if (dr.HasRows)
           {             
              byte[] lesson = (byte[])(dr[0]);
              spathfile = System.IO.Path.GetTempFileName();
              //move from soures to destination the extension until now is .temp
             System.IO.File.Move(spathfile, 
              System.IO.Path.ChangeExtension(spathfile,".pdf"));
                //make it real pdf file  extension .pdf
              spathfile = System.IO.Path.ChangeExtension(spathfile, ".pdf");
               System.IO.File.WriteAllBytes(spathfile, lesson );

               this.axAcroPDF1.LoadFile(spathfile);
         dal.close();
John Paul
  • 12,196
  • 6
  • 55
  • 75
Sulyman
  • 440
  • 5
  • 14
  • 1
    please don't provide code like `"select Lsn_File from Lessons_tbl where Lsn_name = '"TextBox1.Text + "'";` as this is vulnerable to sql injection. – Mathias May 24 '18 at 07:34
  • @Mathias: You might want to check out [this meta question](https://meta.stackoverflow.com/questions/368509/how-to-review-suggested-edits-that-fix-security-issues) about editing security invulnerability in answers. – BDL May 24 '18 at 10:13
  • @BDL: In the linked question it says: `An edit that fixes a potential security flaw in an answer, is a good edit.`. I requested an edit but it got rejected. I'm sorry if I got something wrong. How should this be handled? – Mathias May 24 '18 at 10:45
  • Should have said it clearer: I opened the meta question because of one of your edits. That's an ongoing discussion and I wanted to give you the option to participate in it. – BDL May 24 '18 at 10:50
  • oh, sry didn't saw. – Mathias May 24 '18 at 10:58