Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
  1. Home
  2. General Programming
  3. C#
  4. text file > Binary and Binary > Text file

text file > Binary and Binary > Text file

Scheduled Pinned Locked Moved C#
databasequestionhelptutorial
14 Posts 3 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • L Lost User

    How did you upload the files into your database in the first place? Assuming you used some form of reading the file from disk, then you need to reverse that process to write it back.

    I must get a clever new signature for 2011.

    G Offline
    G Offline
    grmihel2
    wrote on last edited by
    #4

    I used FileStream like this:

    public byte[] ReadFile(string filePath)
    {
    byte[] buffer;
    FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
    try
    {
    int length = (int)fileStream.Length; // get file length
    buffer = new byte[length]; // create buffer
    int count; // actual number of bytes read
    int sum = 0; // total number of bytes read

                // read until Read method returns 0 (end of the stream has been reached)
                while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
                    sum += count;  // sum is a buffer offset for next reading
            }
            finally
            {
                fileStream.Close();
            }
            return buffer;
        }
    

    and stored the returned value byte[] as the varbinary into the Database... Try'd to figure the reverse way back, but didn't worked that well tbh, maybe because I didn't do it the write way, but when I stored it as .docx the file was 'damage' and when I store it as .txt there is just binary numbers.

    L 1 Reply Last reply
    0
    • R Ravi Sant

      Please refer to [this^] example for similar task. What i can say is you can read bytes(varbinary) from SQL database and create a doc file, which you can open and preview to user. But, user cannot do on its own from database.

      G Offline
      G Offline
      grmihel2
      wrote on last edited by
      #5

      The view function is kinda cool, but my problem is, the code ain't ASP, but plain old winforms, and can't find a link between the asp view function and similar function for winforms?

      1 Reply Last reply
      0
      • G grmihel2

        I used FileStream like this:

        public byte[] ReadFile(string filePath)
        {
        byte[] buffer;
        FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read);
        try
        {
        int length = (int)fileStream.Length; // get file length
        buffer = new byte[length]; // create buffer
        int count; // actual number of bytes read
        int sum = 0; // total number of bytes read

                    // read until Read method returns 0 (end of the stream has been reached)
                    while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
                        sum += count;  // sum is a buffer offset for next reading
                }
                finally
                {
                    fileStream.Close();
                }
                return buffer;
            }
        

        and stored the returned value byte[] as the varbinary into the Database... Try'd to figure the reverse way back, but didn't worked that well tbh, maybe because I didn't do it the write way, but when I stored it as .docx the file was 'damage' and when I store it as .txt there is just binary numbers.

        L Offline
        L Offline
        Lost User
        wrote on last edited by
        #6

        Well you have not shown what you did to re-create the file so it is difficult to guess what may be the problem. However, if you merely reverse the process above: get the buffer from the database and write to the appropriate file, then it should be correct.

        grmihel2 wrote:

        when I store it as .txt there is just binary numbers.

        That is to be expected, .docx files are compressed XML.

        I must get a clever new signature for 2011.

        G 1 Reply Last reply
        0
        • L Lost User

          Well you have not shown what you did to re-create the file so it is difficult to guess what may be the problem. However, if you merely reverse the process above: get the buffer from the database and write to the appropriate file, then it should be correct.

          grmihel2 wrote:

          when I store it as .txt there is just binary numbers.

          That is to be expected, .docx files are compressed XML.

          I must get a clever new signature for 2011.

          G Offline
          G Offline
          grmihel2
          wrote on last edited by
          #7

          I try'd the following (had no clue where to start, so just gave it a try with BinaryWriter):

          public void DownloadFile(string filSti, StoredFile fil)
          {
          byte[] file = WriteFile(filSti, fil);
          BinaryWriter bw = new BinaryWriter(File.Open(@"d:\temp\doctest.docx", FileMode.OpenOrCreate));
          bw.Write(file);
          bw.Close();
          }

          Didn't worked that well... It created a .docx file of 32KB (the original was 14KB), and when I try to open it, Word says it cannot be open be cause it may be broken.. Any hint what to do? I have an idea then when I see the light of the end, it would be 'easy' to do the same operation for the PDF documents :)

          L 1 Reply Last reply
          0
          • G grmihel2

            I try'd the following (had no clue where to start, so just gave it a try with BinaryWriter):

            public void DownloadFile(string filSti, StoredFile fil)
            {
            byte[] file = WriteFile(filSti, fil);
            BinaryWriter bw = new BinaryWriter(File.Open(@"d:\temp\doctest.docx", FileMode.OpenOrCreate));
            bw.Write(file);
            bw.Close();
            }

            Didn't worked that well... It created a .docx file of 32KB (the original was 14KB), and when I try to open it, Word says it cannot be open be cause it may be broken.. Any hint what to do? I have an idea then when I see the light of the end, it would be 'easy' to do the same operation for the PDF documents :)

            L Offline
            L Offline
            Lost User
            wrote on last edited by
            #8

            grmihel2 wrote:

            had no clue where to start

            The best thing I can suggest is to look at the classes and methods you are using to read the file, and find the opposite methods for writing. Are you sure that you are reading the file in binary and not using any form of character conversion and thus corrupting the file? Are you verifying every method call is successful and that the captured length of the file matches the original? Also, what does this line do, I've not seen this call?

            byte\[\] file = WriteFile(filSti, fil);
            

            I must get a clever new signature for 2011.

            G 1 Reply Last reply
            0
            • L Lost User

              grmihel2 wrote:

              had no clue where to start

              The best thing I can suggest is to look at the classes and methods you are using to read the file, and find the opposite methods for writing. Are you sure that you are reading the file in binary and not using any form of character conversion and thus corrupting the file? Are you verifying every method call is successful and that the captured length of the file matches the original? Also, what does this line do, I've not seen this call?

              byte\[\] file = WriteFile(filSti, fil);
              

              I must get a clever new signature for 2011.

              G Offline
              G Offline
              grmihel2
              wrote on last edited by
              #9

              Oh yes, sorry, the WriteFile function is following:

              public byte[] WriteFile(string filePath, StoredFile file)
              {
              byte[] buffer = file.FilContent.ToArray();
              FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
              try
              {
              int length = (int)fileStream.Length; // get file length
              buffer = new byte[length]; // create buffer
              int count; // actual number of bytes read
              int sum = 0; // total number of bytes read

                          // read until Read method returns 0 (end of the stream has been reached)
                          while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
                              sum += count;  // sum is a buffer offset for next reading
                  }
                  finally
                  {
                      fileStream.Close();
                  }
              
                  return buffer;
              

              }

              L 1 Reply Last reply
              0
              • G grmihel2

                Oh yes, sorry, the WriteFile function is following:

                public byte[] WriteFile(string filePath, StoredFile file)
                {
                byte[] buffer = file.FilContent.ToArray();
                FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                try
                {
                int length = (int)fileStream.Length; // get file length
                buffer = new byte[length]; // create buffer
                int count; // actual number of bytes read
                int sum = 0; // total number of bytes read

                            // read until Read method returns 0 (end of the stream has been reached)
                            while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
                                sum += count;  // sum is a buffer offset for next reading
                    }
                    finally
                    {
                        fileStream.Close();
                    }
                
                    return buffer;
                

                }

                L Offline
                L Offline
                Lost User
                wrote on last edited by
                #10

                Why are you reading a file in your WriteFile() method? You should be getting the file content from your database and writing it to a disk file. The above code seems somewhat confusing.

                I must get a clever new signature for 2011.

                G 1 Reply Last reply
                0
                • L Lost User

                  Why are you reading a file in your WriteFile() method? You should be getting the file content from your database and writing it to a disk file. The above code seems somewhat confusing.

                  I must get a clever new signature for 2011.

                  G Offline
                  G Offline
                  grmihel2
                  wrote on last edited by
                  #11

                  True, I can see that the Write method didn't make sense :) I'm not really used to do these RW files programming, so I'm sorry for newbieness, but you have to learn it some how :) Anyways, I have attempted to rewrite another write method like this:

                      public void WriteFile(string filePath, StoredFile file)
                      {
                          byte\[\] data = file.FilContent.ToArray();
                          FileStream fileStream = new FileStream(@"d:\\temp\\doctest.docx", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                          try
                          {
                              int length = (int)data.Length;
                              int buffer = 1000;
                  
                              fileStream.SetLength(length);
                              fileStream.Seek(length - buffer, SeekOrigin.Begin);
                              fileStream.Write(data, 0, buffer);
                              fileStream.Flush();
                          }
                          finally
                          {
                              fileStream.Close();
                          }
                      }
                  

                  The doctest.docx file is now 14KB as the original, so something seems right. But the file is still somehow corrupted, cuz I can't open the docx without an error message telling me the data in the Word document is wrong... Notice that the file.Filcontent is the varbinary value from the Database. By the way, is it really so simple, that when I'm sure that its a .docx file I store in my DB as varbinary, I can just store it on local machine as a file with the same extension? No need of creating a Word application object and write it through that?

                  L 1 Reply Last reply
                  0
                  • G grmihel2

                    True, I can see that the Write method didn't make sense :) I'm not really used to do these RW files programming, so I'm sorry for newbieness, but you have to learn it some how :) Anyways, I have attempted to rewrite another write method like this:

                        public void WriteFile(string filePath, StoredFile file)
                        {
                            byte\[\] data = file.FilContent.ToArray();
                            FileStream fileStream = new FileStream(@"d:\\temp\\doctest.docx", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                            try
                            {
                                int length = (int)data.Length;
                                int buffer = 1000;
                    
                                fileStream.SetLength(length);
                                fileStream.Seek(length - buffer, SeekOrigin.Begin);
                                fileStream.Write(data, 0, buffer);
                                fileStream.Flush();
                            }
                            finally
                            {
                                fileStream.Close();
                            }
                        }
                    

                    The doctest.docx file is now 14KB as the original, so something seems right. But the file is still somehow corrupted, cuz I can't open the docx without an error message telling me the data in the Word document is wrong... Notice that the file.Filcontent is the varbinary value from the Database. By the way, is it really so simple, that when I'm sure that its a .docx file I store in my DB as varbinary, I can just store it on local machine as a file with the same extension? No need of creating a Word application object and write it through that?

                    L Offline
                    L Offline
                    Lost User
                    wrote on last edited by
                    #12

                    You seem to be getting confused with your file IO code:

                                int length = (int)data.Length;
                                int buffer = 1000;  // what is this for?
                    
                                fileStream.SetLength(length);  // what is this for?
                                fileStream.Seek(length - buffer, SeekOrigin.Begin);  // what is this for?
                    

                    // fileStream.Write(data, 0, buffer);
                    // instead do
                    fileStream.Write(data, 0, data.Length);
                    fileStream.Flush();

                    I would suggest spending some time here[^] to get a better understanding of the FileStream class.

                    I must get a clever new signature for 2011.

                    G 1 Reply Last reply
                    0
                    • L Lost User

                      You seem to be getting confused with your file IO code:

                                  int length = (int)data.Length;
                                  int buffer = 1000;  // what is this for?
                      
                                  fileStream.SetLength(length);  // what is this for?
                                  fileStream.Seek(length - buffer, SeekOrigin.Begin);  // what is this for?
                      

                      // fileStream.Write(data, 0, buffer);
                      // instead do
                      fileStream.Write(data, 0, data.Length);
                      fileStream.Flush();

                      I would suggest spending some time here[^] to get a better understanding of the FileStream class.

                      I must get a clever new signature for 2011.

                      G Offline
                      G Offline
                      grmihel2
                      wrote on last edited by
                      #13

                      Thanks a lot! That worked like a charm... I certainly need to study some more of the FileStreamers posibilities, thats a whole new world opening, but ain't that the beauty of coding, to explorer new posibilities? :) Yet again, thnx for your expertise, it works brilliant now.

                      L 1 Reply Last reply
                      0
                      • G grmihel2

                        Thanks a lot! That worked like a charm... I certainly need to study some more of the FileStreamers posibilities, thats a whole new world opening, but ain't that the beauty of coding, to explorer new posibilities? :) Yet again, thnx for your expertise, it works brilliant now.

                        L Offline
                        L Offline
                        Lost User
                        wrote on last edited by
                        #14

                        Happy to help, good luck!

                        I must get a clever new signature for 2011.

                        1 Reply Last reply
                        0
                        Reply
                        • Reply as topic
                        Log in to reply
                        • Oldest to Newest
                        • Newest to Oldest
                        • Most Votes


                        • Login

                        • Don't have an account? Register

                        • Login or register to search.
                        • First post
                          Last post
                        0
                        • Categories
                        • Recent
                        • Tags
                        • Popular
                        • World
                        • Users
                        • Groups