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. Converting Back from Decimal to Byte

Converting Back from Decimal to Byte

Scheduled Pinned Locked Moved C#
csharplinqdata-structureshelptutorial
16 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.
  • C Offline
    C Offline
    computerpublic
    wrote on last edited by
    #1

    /*
    First Phase:: I attempting to copy a file off my desktop into a byte array. Then transposing all the bytes into an equivalent decimal array. The decimal array is must (it is very important).

    Second Phase:: I am attempting to convert the same decimal array back to a byte array and write the file back to the desktop or a folder or path.

    The first phase was accomplish with help from the forum, but the second gives me back a garbage file on the desktop. I was attempting to use WriteAllBytes, but I do not know how to use this method. Can you someone please assist me with "WriteAllBytes" or show simply show me how to stop getting garbage file?
    */
    using System;
    using System.IO;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;

    namespace Applica
    {
    class Program
    {
    static void Main(string[] args)
    {
    long Totbyte = 0;
    string filePath = null;
    DirectoryInfo da = new DirectoryInfo("C:\\Folder");
    FileInfo[] Arr = da.GetFiles();

            foreach (FileInfo ap in Arr)
            {
                Totbyte = ap.Length;
                filePath = ap.FullName;
            }
            Console.WriteLine("Total Bytes = {0} bytes", Totbyte);
            string temPath = Path.GetTempFileName();
            byte\[\] data = new byte\[Totbyte\];
    
            if (File.Exists(temPath))
            {
                data = File.ReadAllBytes(filePath);
                File.WriteAllBytes(temPath, data);
            }
            decimal\[\] arry = new decimal\[Totbyte\];
            for (int count = 0; count < data.Length; count++)
            {
                arry\[count\] = data\[count\];
             //   Console.WriteLine("Byte to Decimal = {0},,,,,, count = {1}", arry\[count\], count);
            }
            ///////////ABOVE: READ IN FILE AND CHANGE EACH BYTE TO DECIMAL
            ///////////BELOW: TRYING TO REVERSE THE ABOVE PROCESS
            byte\[\] data2 = new byte\[Totbyte\];
            for (int count = 0; count < arry.Length; count++)
            {
                data2\[count\] = (byte)arry\[count\];
            }
            FileStream file = new FileStream(filePath, FileMode.Create);
            BinaryWriter binarystream = new BinaryWriter(file);
            binarystream.Write(data2);
            binarystream.Close();
        }
    }
    

    }

    Richard DeemingR L 3 Replies Last reply
    0
    • C computerpublic

      /*
      First Phase:: I attempting to copy a file off my desktop into a byte array. Then transposing all the bytes into an equivalent decimal array. The decimal array is must (it is very important).

      Second Phase:: I am attempting to convert the same decimal array back to a byte array and write the file back to the desktop or a folder or path.

      The first phase was accomplish with help from the forum, but the second gives me back a garbage file on the desktop. I was attempting to use WriteAllBytes, but I do not know how to use this method. Can you someone please assist me with "WriteAllBytes" or show simply show me how to stop getting garbage file?
      */
      using System;
      using System.IO;
      using System.Collections.Generic;
      using System.Linq;
      using System.Text;

      namespace Applica
      {
      class Program
      {
      static void Main(string[] args)
      {
      long Totbyte = 0;
      string filePath = null;
      DirectoryInfo da = new DirectoryInfo("C:\\Folder");
      FileInfo[] Arr = da.GetFiles();

              foreach (FileInfo ap in Arr)
              {
                  Totbyte = ap.Length;
                  filePath = ap.FullName;
              }
              Console.WriteLine("Total Bytes = {0} bytes", Totbyte);
              string temPath = Path.GetTempFileName();
              byte\[\] data = new byte\[Totbyte\];
      
              if (File.Exists(temPath))
              {
                  data = File.ReadAllBytes(filePath);
                  File.WriteAllBytes(temPath, data);
              }
              decimal\[\] arry = new decimal\[Totbyte\];
              for (int count = 0; count < data.Length; count++)
              {
                  arry\[count\] = data\[count\];
               //   Console.WriteLine("Byte to Decimal = {0},,,,,, count = {1}", arry\[count\], count);
              }
              ///////////ABOVE: READ IN FILE AND CHANGE EACH BYTE TO DECIMAL
              ///////////BELOW: TRYING TO REVERSE THE ABOVE PROCESS
              byte\[\] data2 = new byte\[Totbyte\];
              for (int count = 0; count < arry.Length; count++)
              {
                  data2\[count\] = (byte)arry\[count\];
              }
              FileStream file = new FileStream(filePath, FileMode.Create);
              BinaryWriter binarystream = new BinaryWriter(file);
              binarystream.Write(data2);
              binarystream.Close();
          }
      }
      

      }

      Richard DeemingR Offline
      Richard DeemingR Offline
      Richard Deeming
      wrote on last edited by
      #2

      Firstly, why have you reposted this question when Harold is already helping you on your previous copy of this question[^]? Secondly, the code you have posted does not produce a "garbage file". The bytes in data2 will match the bytes in data exactly. You will end up overwriting the original file with an exact copy of itself. Thirdly, you state that you don't know how to use the File.WriteAllBytes method, and yet you have a perfectly valid example of it in your code! Cleaning up your code, replacing the BinaryWriter with File.WriteAllBytes, and adding some sanity checks:

      DirectoryInfo da = new DirectoryInfo("C:\\Folder");
      FileInfo[] Arr = da.GetFiles();
      if (Arr.Length == 0)
      {
      throw new InvalidOperationException("No files found.");
      }

      // No need to loop through the array just to get the last item:
      FileInfo ap = Arr[Arr.Length - 1];
      long Totbyte = ap.Length;
      string filePath = ap.FullName;
      Console.WriteLine("Total Bytes = {0} bytes", Totbyte);

      // GetTempFileName *creates* the file, so it always exists:
      string temPath = Path.GetTempFileName();
      byte[] data = File.ReadAllBytes(filePath);
      File.WriteAllBytes(temPath, data);

      // Convert the bytes to decimals:
      decimal[] arry = new decimal[Totbyte];
      for (int count = 0; count < data.Length; count++)
      {
      arry[count] = data[count];
      }

      // Convert the decimals back to bytes:
      byte[] data2 = new byte[Totbyte];
      for (int count = 0; count < arry.Length; count++)
      {
      data2[count] = (byte)arry[count];
      }

      // Just to prove they're the same:
      if (data2.Length != data.Length)
      {
      throw new InvalidOperationException("Wrong length!");
      }
      for (int index = 0; index < data.Length; index++)
      {
      if (data[index] != data2[index])
      {
      throw new InvalidOperationException("Data has changed at index " + index);
      }
      }

      // Write the bytes back to the file:
      File.WriteAllBytes(filePath, data2);

      // To prove they're still the same:
      data = File.ReadAllBytes(temPath);
      data2 = File.ReadAllBytes(filePath);

      if (data2.Length != data.Length)
      {
      throw new InvalidOperationException("Wrong length!");
      }
      for (int index = 0; index < data.Length; index++)
      {
      if (data[index] != data2[index])
      {

      "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

      C 1 Reply Last reply
      0
      • C computerpublic

        /*
        First Phase:: I attempting to copy a file off my desktop into a byte array. Then transposing all the bytes into an equivalent decimal array. The decimal array is must (it is very important).

        Second Phase:: I am attempting to convert the same decimal array back to a byte array and write the file back to the desktop or a folder or path.

        The first phase was accomplish with help from the forum, but the second gives me back a garbage file on the desktop. I was attempting to use WriteAllBytes, but I do not know how to use this method. Can you someone please assist me with "WriteAllBytes" or show simply show me how to stop getting garbage file?
        */
        using System;
        using System.IO;
        using System.Collections.Generic;
        using System.Linq;
        using System.Text;

        namespace Applica
        {
        class Program
        {
        static void Main(string[] args)
        {
        long Totbyte = 0;
        string filePath = null;
        DirectoryInfo da = new DirectoryInfo("C:\\Folder");
        FileInfo[] Arr = da.GetFiles();

                foreach (FileInfo ap in Arr)
                {
                    Totbyte = ap.Length;
                    filePath = ap.FullName;
                }
                Console.WriteLine("Total Bytes = {0} bytes", Totbyte);
                string temPath = Path.GetTempFileName();
                byte\[\] data = new byte\[Totbyte\];
        
                if (File.Exists(temPath))
                {
                    data = File.ReadAllBytes(filePath);
                    File.WriteAllBytes(temPath, data);
                }
                decimal\[\] arry = new decimal\[Totbyte\];
                for (int count = 0; count < data.Length; count++)
                {
                    arry\[count\] = data\[count\];
                 //   Console.WriteLine("Byte to Decimal = {0},,,,,, count = {1}", arry\[count\], count);
                }
                ///////////ABOVE: READ IN FILE AND CHANGE EACH BYTE TO DECIMAL
                ///////////BELOW: TRYING TO REVERSE THE ABOVE PROCESS
                byte\[\] data2 = new byte\[Totbyte\];
                for (int count = 0; count < arry.Length; count++)
                {
                    data2\[count\] = (byte)arry\[count\];
                }
                FileStream file = new FileStream(filePath, FileMode.Create);
                BinaryWriter binarystream = new BinaryWriter(file);
                binarystream.Write(data2);
                binarystream.Close();
            }
        }
        

        }

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

        Totbyte isn't set in your version and remains 0. Had you not initialized the variable with 0 then the compiler would have warned you. Tis set. To the size of the last file in the folder. :doh: ..off for some :zzz:

        Bastard Programmer from Hell :suss: If you can't read my code, try converting it here[^]

        1 Reply Last reply
        0
        • Richard DeemingR Richard Deeming

          Firstly, why have you reposted this question when Harold is already helping you on your previous copy of this question[^]? Secondly, the code you have posted does not produce a "garbage file". The bytes in data2 will match the bytes in data exactly. You will end up overwriting the original file with an exact copy of itself. Thirdly, you state that you don't know how to use the File.WriteAllBytes method, and yet you have a perfectly valid example of it in your code! Cleaning up your code, replacing the BinaryWriter with File.WriteAllBytes, and adding some sanity checks:

          DirectoryInfo da = new DirectoryInfo("C:\\Folder");
          FileInfo[] Arr = da.GetFiles();
          if (Arr.Length == 0)
          {
          throw new InvalidOperationException("No files found.");
          }

          // No need to loop through the array just to get the last item:
          FileInfo ap = Arr[Arr.Length - 1];
          long Totbyte = ap.Length;
          string filePath = ap.FullName;
          Console.WriteLine("Total Bytes = {0} bytes", Totbyte);

          // GetTempFileName *creates* the file, so it always exists:
          string temPath = Path.GetTempFileName();
          byte[] data = File.ReadAllBytes(filePath);
          File.WriteAllBytes(temPath, data);

          // Convert the bytes to decimals:
          decimal[] arry = new decimal[Totbyte];
          for (int count = 0; count < data.Length; count++)
          {
          arry[count] = data[count];
          }

          // Convert the decimals back to bytes:
          byte[] data2 = new byte[Totbyte];
          for (int count = 0; count < arry.Length; count++)
          {
          data2[count] = (byte)arry[count];
          }

          // Just to prove they're the same:
          if (data2.Length != data.Length)
          {
          throw new InvalidOperationException("Wrong length!");
          }
          for (int index = 0; index < data.Length; index++)
          {
          if (data[index] != data2[index])
          {
          throw new InvalidOperationException("Data has changed at index " + index);
          }
          }

          // Write the bytes back to the file:
          File.WriteAllBytes(filePath, data2);

          // To prove they're still the same:
          data = File.ReadAllBytes(temPath);
          data2 = File.ReadAllBytes(filePath);

          if (data2.Length != data.Length)
          {
          throw new InvalidOperationException("Wrong length!");
          }
          for (int index = 0; index < data.Length; index++)
          {
          if (data[index] != data2[index])
          {

          C Offline
          C Offline
          computerpublic
          wrote on last edited by
          #4

          Can you put the new file in another directory so I can have two files to compare later? Or maybe just change the name so i can have two files to compare?

          Richard DeemingR 1 Reply Last reply
          0
          • C computerpublic

            /*
            First Phase:: I attempting to copy a file off my desktop into a byte array. Then transposing all the bytes into an equivalent decimal array. The decimal array is must (it is very important).

            Second Phase:: I am attempting to convert the same decimal array back to a byte array and write the file back to the desktop or a folder or path.

            The first phase was accomplish with help from the forum, but the second gives me back a garbage file on the desktop. I was attempting to use WriteAllBytes, but I do not know how to use this method. Can you someone please assist me with "WriteAllBytes" or show simply show me how to stop getting garbage file?
            */
            using System;
            using System.IO;
            using System.Collections.Generic;
            using System.Linq;
            using System.Text;

            namespace Applica
            {
            class Program
            {
            static void Main(string[] args)
            {
            long Totbyte = 0;
            string filePath = null;
            DirectoryInfo da = new DirectoryInfo("C:\\Folder");
            FileInfo[] Arr = da.GetFiles();

                    foreach (FileInfo ap in Arr)
                    {
                        Totbyte = ap.Length;
                        filePath = ap.FullName;
                    }
                    Console.WriteLine("Total Bytes = {0} bytes", Totbyte);
                    string temPath = Path.GetTempFileName();
                    byte\[\] data = new byte\[Totbyte\];
            
                    if (File.Exists(temPath))
                    {
                        data = File.ReadAllBytes(filePath);
                        File.WriteAllBytes(temPath, data);
                    }
                    decimal\[\] arry = new decimal\[Totbyte\];
                    for (int count = 0; count < data.Length; count++)
                    {
                        arry\[count\] = data\[count\];
                     //   Console.WriteLine("Byte to Decimal = {0},,,,,, count = {1}", arry\[count\], count);
                    }
                    ///////////ABOVE: READ IN FILE AND CHANGE EACH BYTE TO DECIMAL
                    ///////////BELOW: TRYING TO REVERSE THE ABOVE PROCESS
                    byte\[\] data2 = new byte\[Totbyte\];
                    for (int count = 0; count < arry.Length; count++)
                    {
                        data2\[count\] = (byte)arry\[count\];
                    }
                    FileStream file = new FileStream(filePath, FileMode.Create);
                    BinaryWriter binarystream = new BinaryWriter(file);
                    binarystream.Write(data2);
                    binarystream.Close();
                }
            }
            

            }

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

            I would be interested to know exactly what you are trying to achieve with this, particularly as you say it is important to create the decimal array. You read an array of bytes from a file, and copy it to an array of decimals (each element 16 bytes long). You then copy those decimals back to an array of bytes, i.e back to the original, and write them out to a file. So both files contain exactly the same data.

            Veni, vidi, abiit domum

            1 Reply Last reply
            0
            • C computerpublic

              Can you put the new file in another directory so I can have two files to compare later? Or maybe just change the name so i can have two files to compare?

              Richard DeemingR Offline
              Richard DeemingR Offline
              Richard Deeming
              wrote on last edited by
              #6

              Yes, you just need to change the path in your WriteAllBytes call:

              // Write the bytes to a different file:
              string filePath2 = Path.Combine("C:\\A Different Folder", Path.GetFileName(filePath));
              File.WriteAllBytes(filePath2, data2);


              "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

              "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

              C 1 Reply Last reply
              0
              • Richard DeemingR Richard Deeming

                Yes, you just need to change the path in your WriteAllBytes call:

                // Write the bytes to a different file:
                string filePath2 = Path.Combine("C:\\A Different Folder", Path.GetFileName(filePath));
                File.WriteAllBytes(filePath2, data2);


                "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                C Offline
                C Offline
                computerpublic
                wrote on last edited by
                #7

                /*
                IT DOESN'T WORK..I ADDED THE LINE:::string filePath2 = Path.Combine("C:\\check", Path.GetFileName(filePath));
                I RAN THE PROGRAM AND CHECK FOLDER WAS EMPTY. THE FILE WAS NOT WRITTEN TO THE NEW LOCATION. ALL I WANT TO DO SEE ANOTHER INSTANCE OF THE FILE
                */

                using System;
                using System.IO;
                using System.Collections.Generic;
                using System.Linq;
                using System.Text;

                namespace Applica
                {
                class Program
                {
                static void Main(string[] args)
                {
                DirectoryInfo da = new DirectoryInfo("C:\\Folder");
                FileInfo[] Arr = da.GetFiles();
                if (Arr.Length == 0)
                {
                throw new InvalidOperationException("No files found.");
                }
                // No need to loop through the array just to get the last item:
                FileInfo ap = Arr[Arr.Length - 1];
                long Totbyte = ap.Length;
                string filePath = ap.FullName;
                Console.WriteLine("Total Bytes = {0} bytes", Totbyte);
                // GetTempFileName *creates* the file, so it always exists:
                string temPath = Path.GetTempFileName();
                byte[] data = File.ReadAllBytes(filePath);
                File.WriteAllBytes(temPath, data);
                // Convert the bytes to decimals:
                decimal[] arry = new decimal[Totbyte];
                for (int count = 0; count < data.Length; count++)
                {
                arry[count] = data[count];
                }
                // Convert the decimals back to bytes:
                byte[] data2 = new byte[Totbyte];
                for (int count = 0; count < arry.Length; count++)
                {
                data2[count] = (byte)arry[count];
                }
                // Just to prove they're the same:
                if (data2.Length != data.Length)
                {
                throw new InvalidOperationException("Wrong length!");
                }
                for (int index = 0; index < data.Length; index++)
                {
                if (data[index] != data2[index])
                {
                throw new InvalidOperationException("Data has changed at index " + index);
                }
                }
                // Write the bytes back to the file:
                string filePath2 = Path.Combine("C:\\check", Path.GetFileName(filePath));
                File.WriteAllBytes(filePath, data2);
                // To prove they're still the same:
                data = File.ReadAllBytes(temPath);
                data2 = File.ReadAllBytes(filePath);
                if (

                Richard DeemingR 1 Reply Last reply
                0
                • C computerpublic

                  /*
                  IT DOESN'T WORK..I ADDED THE LINE:::string filePath2 = Path.Combine("C:\\check", Path.GetFileName(filePath));
                  I RAN THE PROGRAM AND CHECK FOLDER WAS EMPTY. THE FILE WAS NOT WRITTEN TO THE NEW LOCATION. ALL I WANT TO DO SEE ANOTHER INSTANCE OF THE FILE
                  */

                  using System;
                  using System.IO;
                  using System.Collections.Generic;
                  using System.Linq;
                  using System.Text;

                  namespace Applica
                  {
                  class Program
                  {
                  static void Main(string[] args)
                  {
                  DirectoryInfo da = new DirectoryInfo("C:\\Folder");
                  FileInfo[] Arr = da.GetFiles();
                  if (Arr.Length == 0)
                  {
                  throw new InvalidOperationException("No files found.");
                  }
                  // No need to loop through the array just to get the last item:
                  FileInfo ap = Arr[Arr.Length - 1];
                  long Totbyte = ap.Length;
                  string filePath = ap.FullName;
                  Console.WriteLine("Total Bytes = {0} bytes", Totbyte);
                  // GetTempFileName *creates* the file, so it always exists:
                  string temPath = Path.GetTempFileName();
                  byte[] data = File.ReadAllBytes(filePath);
                  File.WriteAllBytes(temPath, data);
                  // Convert the bytes to decimals:
                  decimal[] arry = new decimal[Totbyte];
                  for (int count = 0; count < data.Length; count++)
                  {
                  arry[count] = data[count];
                  }
                  // Convert the decimals back to bytes:
                  byte[] data2 = new byte[Totbyte];
                  for (int count = 0; count < arry.Length; count++)
                  {
                  data2[count] = (byte)arry[count];
                  }
                  // Just to prove they're the same:
                  if (data2.Length != data.Length)
                  {
                  throw new InvalidOperationException("Wrong length!");
                  }
                  for (int index = 0; index < data.Length; index++)
                  {
                  if (data[index] != data2[index])
                  {
                  throw new InvalidOperationException("Data has changed at index " + index);
                  }
                  }
                  // Write the bytes back to the file:
                  string filePath2 = Path.Combine("C:\\check", Path.GetFileName(filePath));
                  File.WriteAllBytes(filePath, data2);
                  // To prove they're still the same:
                  data = File.ReadAllBytes(temPath);
                  data2 = File.ReadAllBytes(filePath);
                  if (

                  Richard DeemingR Offline
                  Richard DeemingR Offline
                  Richard Deeming
                  wrote on last edited by
                  #8

                  computerpublic wrote:

                  string filePath2 = Path.Combine("C:\\check", Path.GetFileName(filePath)); File.WriteAllBytes(filePath, data2);

                  If you want to write the bytes to the file whose path is stored in the filePath2 variable, then you need to pass that variable to the WriteAllBytes method, as I showed you in my previous answer[^].

                  // Write the bytes to a different file:
                  string filePath2 = Path.Combine("C:\\check", Path.GetFileName(filePath));
                  File.WriteAllBytes(filePath2, data2); // <-- NB: Pass filePath2 here, not filePath!


                  "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                  "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                  C 3 Replies Last reply
                  0
                  • Richard DeemingR Richard Deeming

                    computerpublic wrote:

                    string filePath2 = Path.Combine("C:\\check", Path.GetFileName(filePath)); File.WriteAllBytes(filePath, data2);

                    If you want to write the bytes to the file whose path is stored in the filePath2 variable, then you need to pass that variable to the WriteAllBytes method, as I showed you in my previous answer[^].

                    // Write the bytes to a different file:
                    string filePath2 = Path.Combine("C:\\check", Path.GetFileName(filePath));
                    File.WriteAllBytes(filePath2, data2); // <-- NB: Pass filePath2 here, not filePath!


                    "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                    C Offline
                    C Offline
                    computerpublic
                    wrote on last edited by
                    #9

                    It works. Thank you very much Richard.

                    1 Reply Last reply
                    0
                    • Richard DeemingR Richard Deeming

                      computerpublic wrote:

                      string filePath2 = Path.Combine("C:\\check", Path.GetFileName(filePath)); File.WriteAllBytes(filePath, data2);

                      If you want to write the bytes to the file whose path is stored in the filePath2 variable, then you need to pass that variable to the WriteAllBytes method, as I showed you in my previous answer[^].

                      // Write the bytes to a different file:
                      string filePath2 = Path.Combine("C:\\check", Path.GetFileName(filePath));
                      File.WriteAllBytes(filePath2, data2); // <-- NB: Pass filePath2 here, not filePath!


                      "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                      C Offline
                      C Offline
                      computerpublic
                      wrote on last edited by
                      #10

                      /*
                      I AM NOW TRYING TO CONVERT BYTE TO STRING AND ALSO CONVERTING BACK FROM STRING TO BYTE.
                      I ALSO WANT TO SEE THE OUTPUT.
                      I AM NOT UNDERSTING WHY I AM GETTING AN ERROR.
                      THE OUTPUT INFORMATION IS BELOW::

                      Total Bytes = 8228730 bytes

                      Unhandled Exception: System.InvalidOperationException: Data has changed at index
                      310
                      at Applica.Program.Main(String[] args) in C:\Documents and Settings\shampro\D
                      esktop\Program.cs:line 41
                      Press any key to continue . . .
                      */

                      using System;
                      using System.IO;
                      using System.Collections.Generic;
                      using System.Linq;
                      using System.Text;

                      namespace Applica
                      {
                      class Program
                      {
                      static void Main(string[] args)
                      {
                      DirectoryInfo da = new DirectoryInfo("C:\\Folder");
                      FileInfo[] Arr = da.GetFiles();
                      if (Arr.Length == 0)
                      {
                      throw new InvalidOperationException("No files found.");
                      }
                      // No need to loop through the array just to get the last item:
                      FileInfo ap = Arr[Arr.Length - 1];
                      long Totbyte = ap.Length;
                      string filePath = ap.FullName;
                      Console.WriteLine("Total Bytes = {0} bytes", Totbyte);
                      // GetTempFileName *creates* the file, so it always exists:
                      string temPath = Path.GetTempFileName();
                      byte[] data = File.ReadAllBytes(filePath);
                      File.WriteAllBytes(temPath, data);
                      // Convert the bytes to string:
                      string arry = ASCIIEncoding.ASCII.GetString(data);
                      Console.WriteLine(arry);
                      // Convert the string back to bytes:
                      byte[] data2 = Encoding.ASCII.GetBytes(arry);
                      foreach (byte element in data2)
                      {
                      Console.WriteLine("{0}={1}",element ,(char)element);
                      }
                      // Just to prove they're the same:
                      if (data2.Length != data.Length)
                      {
                      throw new InvalidOperationException("Wrong length!");
                      }
                      for (int index = 0; index < data.Length; index++)
                      {
                      if (data[index] != data2[index])
                      {
                      throw new InvalidOperationException("Data has changed at index " + index);
                      }
                      }
                      // Write the bytes back to the file:
                      string filePath2 = Path.Combine("C:\\check", Path.GetFileName(filePath));
                      File.WriteAllBytes(filePath2, data2);
                      // To prove they're

                      C Richard DeemingR 2 Replies Last reply
                      0
                      • C computerpublic

                        /*
                        I AM NOW TRYING TO CONVERT BYTE TO STRING AND ALSO CONVERTING BACK FROM STRING TO BYTE.
                        I ALSO WANT TO SEE THE OUTPUT.
                        I AM NOT UNDERSTING WHY I AM GETTING AN ERROR.
                        THE OUTPUT INFORMATION IS BELOW::

                        Total Bytes = 8228730 bytes

                        Unhandled Exception: System.InvalidOperationException: Data has changed at index
                        310
                        at Applica.Program.Main(String[] args) in C:\Documents and Settings\shampro\D
                        esktop\Program.cs:line 41
                        Press any key to continue . . .
                        */

                        using System;
                        using System.IO;
                        using System.Collections.Generic;
                        using System.Linq;
                        using System.Text;

                        namespace Applica
                        {
                        class Program
                        {
                        static void Main(string[] args)
                        {
                        DirectoryInfo da = new DirectoryInfo("C:\\Folder");
                        FileInfo[] Arr = da.GetFiles();
                        if (Arr.Length == 0)
                        {
                        throw new InvalidOperationException("No files found.");
                        }
                        // No need to loop through the array just to get the last item:
                        FileInfo ap = Arr[Arr.Length - 1];
                        long Totbyte = ap.Length;
                        string filePath = ap.FullName;
                        Console.WriteLine("Total Bytes = {0} bytes", Totbyte);
                        // GetTempFileName *creates* the file, so it always exists:
                        string temPath = Path.GetTempFileName();
                        byte[] data = File.ReadAllBytes(filePath);
                        File.WriteAllBytes(temPath, data);
                        // Convert the bytes to string:
                        string arry = ASCIIEncoding.ASCII.GetString(data);
                        Console.WriteLine(arry);
                        // Convert the string back to bytes:
                        byte[] data2 = Encoding.ASCII.GetBytes(arry);
                        foreach (byte element in data2)
                        {
                        Console.WriteLine("{0}={1}",element ,(char)element);
                        }
                        // Just to prove they're the same:
                        if (data2.Length != data.Length)
                        {
                        throw new InvalidOperationException("Wrong length!");
                        }
                        for (int index = 0; index < data.Length; index++)
                        {
                        if (data[index] != data2[index])
                        {
                        throw new InvalidOperationException("Data has changed at index " + index);
                        }
                        }
                        // Write the bytes back to the file:
                        string filePath2 = Path.Combine("C:\\check", Path.GetFileName(filePath));
                        File.WriteAllBytes(filePath2, data2);
                        // To prove they're

                        C Offline
                        C Offline
                        computerpublic
                        wrote on last edited by
                        #11

                        SORRY, THE PROBLEM IS ON LINE 61. BEFORE THE PROBLEM WAS ON LINE 41, BUT I ADDED COMMENTS AND SHIFTED THE ENTIRE THING DOWN.

                        1 Reply Last reply
                        0
                        • C computerpublic

                          /*
                          I AM NOW TRYING TO CONVERT BYTE TO STRING AND ALSO CONVERTING BACK FROM STRING TO BYTE.
                          I ALSO WANT TO SEE THE OUTPUT.
                          I AM NOT UNDERSTING WHY I AM GETTING AN ERROR.
                          THE OUTPUT INFORMATION IS BELOW::

                          Total Bytes = 8228730 bytes

                          Unhandled Exception: System.InvalidOperationException: Data has changed at index
                          310
                          at Applica.Program.Main(String[] args) in C:\Documents and Settings\shampro\D
                          esktop\Program.cs:line 41
                          Press any key to continue . . .
                          */

                          using System;
                          using System.IO;
                          using System.Collections.Generic;
                          using System.Linq;
                          using System.Text;

                          namespace Applica
                          {
                          class Program
                          {
                          static void Main(string[] args)
                          {
                          DirectoryInfo da = new DirectoryInfo("C:\\Folder");
                          FileInfo[] Arr = da.GetFiles();
                          if (Arr.Length == 0)
                          {
                          throw new InvalidOperationException("No files found.");
                          }
                          // No need to loop through the array just to get the last item:
                          FileInfo ap = Arr[Arr.Length - 1];
                          long Totbyte = ap.Length;
                          string filePath = ap.FullName;
                          Console.WriteLine("Total Bytes = {0} bytes", Totbyte);
                          // GetTempFileName *creates* the file, so it always exists:
                          string temPath = Path.GetTempFileName();
                          byte[] data = File.ReadAllBytes(filePath);
                          File.WriteAllBytes(temPath, data);
                          // Convert the bytes to string:
                          string arry = ASCIIEncoding.ASCII.GetString(data);
                          Console.WriteLine(arry);
                          // Convert the string back to bytes:
                          byte[] data2 = Encoding.ASCII.GetBytes(arry);
                          foreach (byte element in data2)
                          {
                          Console.WriteLine("{0}={1}",element ,(char)element);
                          }
                          // Just to prove they're the same:
                          if (data2.Length != data.Length)
                          {
                          throw new InvalidOperationException("Wrong length!");
                          }
                          for (int index = 0; index < data.Length; index++)
                          {
                          if (data[index] != data2[index])
                          {
                          throw new InvalidOperationException("Data has changed at index " + index);
                          }
                          }
                          // Write the bytes back to the file:
                          string filePath2 = Path.Combine("C:\\check", Path.GetFileName(filePath));
                          File.WriteAllBytes(filePath2, data2);
                          // To prove they're

                          Richard DeemingR Offline
                          Richard DeemingR Offline
                          Richard Deeming
                          wrote on last edited by
                          #12

                          Hardly surprising - ASCII encoding can only cope with 128 characters. If any of your bytes are greater than or equal to 128, the ASCIIEncoding class[^] will replace them with a question mark. When you re-encode the string, these bytes will have been replaced with the value 63. You still haven't explained what you're trying to achieve.


                          "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                          "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                          C 1 Reply Last reply
                          0
                          • Richard DeemingR Richard Deeming

                            Hardly surprising - ASCII encoding can only cope with 128 characters. If any of your bytes are greater than or equal to 128, the ASCIIEncoding class[^] will replace them with a question mark. When you re-encode the string, these bytes will have been replaced with the value 63. You still haven't explained what you're trying to achieve.


                            "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                            C Offline
                            C Offline
                            computerpublic
                            wrote on last edited by
                            #13

                            I am trying to become a good programmer, but following the examples in the books sometimes does not work. The professor in the school is also very suspicious. I think she is reading the chapters before the class and pretending like she knows. She never answers direct questions. The answer always come in the next class session. I feel I am on my own with c#. Sometimes I feel that the people who write the books, don't know any c# at all. How it is possible for examples in text not to work. I encounter this problem many times and it is very frustrating. To add to the frustration, I go online to the help forums and I continually being ask "What are you trying to achieve"? As if a non programmer is not allowed to ask questions and learn from people who know. I am trying to learn from people who know, that is what I am trying to achieve. I hope this answers the question.

                            C Richard DeemingR 2 Replies Last reply
                            0
                            • C computerpublic

                              I am trying to become a good programmer, but following the examples in the books sometimes does not work. The professor in the school is also very suspicious. I think she is reading the chapters before the class and pretending like she knows. She never answers direct questions. The answer always come in the next class session. I feel I am on my own with c#. Sometimes I feel that the people who write the books, don't know any c# at all. How it is possible for examples in text not to work. I encounter this problem many times and it is very frustrating. To add to the frustration, I go online to the help forums and I continually being ask "What are you trying to achieve"? As if a non programmer is not allowed to ask questions and learn from people who know. I am trying to learn from people who know, that is what I am trying to achieve. I hope this answers the question.

                              C Offline
                              C Offline
                              computerpublic
                              wrote on last edited by
                              #14

                              Could you please kindly respond to my new post "Out Of Memory Exception"? It is a completely different question, so I didn't thought it wise to post it here. Thank You.

                              1 Reply Last reply
                              0
                              • C computerpublic

                                I am trying to become a good programmer, but following the examples in the books sometimes does not work. The professor in the school is also very suspicious. I think she is reading the chapters before the class and pretending like she knows. She never answers direct questions. The answer always come in the next class session. I feel I am on my own with c#. Sometimes I feel that the people who write the books, don't know any c# at all. How it is possible for examples in text not to work. I encounter this problem many times and it is very frustrating. To add to the frustration, I go online to the help forums and I continually being ask "What are you trying to achieve"? As if a non programmer is not allowed to ask questions and learn from people who know. I am trying to learn from people who know, that is what I am trying to achieve. I hope this answers the question.

                                Richard DeemingR Offline
                                Richard DeemingR Offline
                                Richard Deeming
                                wrote on last edited by
                                #15

                                computerpublic wrote:

                                I continually being ask "What are you trying to achieve"? As if a non programmer is not allowed to ask questions and learn from people who know.

                                We don't ask what you're trying to achieve because we don't want you asking questions; it's just that, if you tell us what you want the code to do, we might be able to point you towards a better solution. It's often better to take a step back and look at the bigger picture of what you want to do, rather than fixating on why a particular line of code doesn't do what you expect. :) Your professor certainly doesn't sound like she's up to the job. Have you tried talking to your tutor about your concerns?


                                "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                                "These people looked deep within my soul and assigned me a number based on the order in which I joined" - Homer

                                1 Reply Last reply
                                0
                                • Richard DeemingR Richard Deeming

                                  computerpublic wrote:

                                  string filePath2 = Path.Combine("C:\\check", Path.GetFileName(filePath)); File.WriteAllBytes(filePath, data2);

                                  If you want to write the bytes to the file whose path is stored in the filePath2 variable, then you need to pass that variable to the WriteAllBytes method, as I showed you in my previous answer[^].

                                  // Write the bytes to a different file:
                                  string filePath2 = Path.Combine("C:\\check", Path.GetFileName(filePath));
                                  File.WriteAllBytes(filePath2, data2); // <-- NB: Pass filePath2 here, not filePath!


                                  "These people looked deep within my soul and assigned me a number based on the order in which I joined." - Homer

                                  C Offline
                                  C Offline
                                  computerpublic
                                  wrote on last edited by
                                  #16

                                  /*If I am generating a series of bits ONE BIT AT A TIME for example {10101000}. How do I turn the entire series into one byte after I generate the 8th bit. I am trying to back track using the example you gave me, but I am getting some errors.*/

                                  using System;
                                  using System.IO;
                                  using System.Collections;
                                  using System.Collections.Generic;
                                  using System.Linq;
                                  using System.Text;

                                  namespace Applica
                                  {
                                  class Program
                                  {
                                  static Random _random = new Random ();////Start: Fisher-Yates Array Shuffler
                                  public static void Shuffle<T>(T[] array)
                                  {
                                  var random = _random;
                                  for (int i = array.Length; i > 1; i--)
                                  {
                                  int j = random.Next(i);
                                  T tmp = array[j];
                                  array[j] = array[i - 1];
                                  array[i - 1] = tmp;
                                  }
                                  }////////////////////////////////////////////End: Fisher-Yates Array Shuffer
                                  static void Main(string[] args)
                                  {
                                  byte[] outdata = new byte[1];
                                  BitArray[] bits2 = new BitArray[8];
                                  char[] array = {'1','0','1','0','1','0','1','0'};
                                  Shuffle(array);
                                  for (int i = 0; i < 8; i++)
                                  bits2[i] = array[1];//Error: Cannot Implicitly convert type 'char' to 'System.Collections.BitArray'
                                  outdata[i] = (byte)bits2;//Error: Cannot convert type 'System.Collections.BitArray[]' to 'byte'
                                  }
                                  }
                                  }

                                  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