Thread: C# beginner FileStream help please

  1. #1
    Registered User
    Join Date
    Aug 2009
    Posts
    16

    C# beginner FileStream help please

    Hi guys,

    I am currently trying to read the first 512 bytes of a series of files into array entries for future use. i.e.
    files [file 1 contents]
    files [file 2 contents] etc etc...

    So far with my very limited time with C# (I started yesterday!) I have cobbled this together which will pick the files from a folder, and read the first 512 bytes to console.write() just to show me that it is getting the data.

    I know in C I could just use pointers, but I understand they are not really used in #?

    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    
    class Program
    {
        static void Main()
        {
    
            // Put all exe files in root directory into array.
            string[] array2 = Directory.GetFiles(@"C:\Dev-Cpp\", "*.EXE");
            
            // Display all BIN files.
            Console.WriteLine(@"C:\Dev-Cpp\");
            Console.WriteLine("--- EXE Files: ---");
    
            foreach (string name in array2)
            {
                Console.WriteLine(name);
            }
    
            for (int print = 0; print < array2.Length; print++)
            {
                FileStream myFStream = new FileStream(array2[print], FileMode.OpenOrCreate, FileAccess.ReadWrite);
              
                Console.WriteLine("Contents of file {0}: ", array2[print]);
    
                for (int i = 0; i < 512; i++)
                {
                    Console.Write(myFStream.ReadByte());
    
                    //debugging space to print each byte to screen
                    Console.Write(" ");                
                }
    
                Console.WriteLine();
                myFStream.Close();
    
            }
    
            Console.ReadKey();
    
        }
    
    }
    Any help, advice, links to relevant content greatly appreciated

    Cheers,

    Ben

  2. #2
    Confused Magos's Avatar
    Join Date
    Sep 2001
    Location
    Sweden
    Posts
    3,145
    Reading one byte at a time is a pretty inefficient method.
    Use this method instead: Stream.Read Method (System.IO)
    (create a 512-byte buffer that you pass to it)
    MagosX.com

    Give a man a fish and you feed him for a day.
    Teach a man to fish and you feed him for a lifetime.

  3. #3
    Registered User
    Join Date
    Sep 2011
    Posts
    71
    suchthefool, I am not sure what your question is, but the following comes to mind: use the System.IO.StreamReader class and pass the FileStream instance as an argument to the constructor. Then use the StreamReader's method to read the contents of the files.

    Hope that helps.

  4. #4
    Registered User
    Join Date
    Aug 2003
    Posts
    1,218
    Considering he is reading EXE-files i would not advice to use StreamReader. The StreamReader class is more for reading simple text files and not binary files as the OP suggests.

  5. #5
    Registered User
    Join Date
    Aug 2009
    Posts
    16
    I did read into StreamReader and a few other things. Reading .txt files is off the cards. Thank-you for all your replies!

    I have spent the day re-writing and googling everything and anything, decided to re-write the code and have scrapped the 512 bytes read. Now I am searching the FileStream for fragments of data. But am having issues as the fragments to search for are char strings stored in array elements, and obviously the .exe files are not read in the type char.

    In ANSI C I would just declare two integer strings and to read data into and compare ascii values between the two.....

    Here is the changed code from today if anybody has any tips

    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.IO;
    
    public class mainProgram
    {
        //code to list all files with extension .exe and store their locations 
        //in a string array
        public static void Main()
        {
    
            string[] directories = Directory.GetDirectories(@"C:\DEV-CPP\");
            string[] currentDirectoryContents = Directory.GetFiles(@"C:\DEV-CPP\", "*.EXE");
           
            //test to check a string for content
            bool[] test = new bool[currentDirectoryContents.Length];
            string[] infectedFiles = new string[currentDirectoryContents.Length];
            string[] definitions = File.ReadAllLines(@"C:\definitions.txt");
            
            int infected = 0;
    
            for (int i = 0; i < definitions.Length; i++)
            {
                for (int j = 0; j < currentDirectoryContents.Length; j++)
                {
                    byte[] buffer = File.ReadAllBytes(currentDirectoryContents[j]);
                    string base64Encoded = Convert.ToString(buffer);
                    test[j] = base64Encoded.Contains(definitions[i]);
                    if (test[j] == true)
                    {
                        infectedFiles[infected] = currentDirectoryContents[j];
                        infected++;
                    }
    
                }
            }
    
                               
            if (infected >= 1)
            {
                Console.WriteLine("Your scan matched {0} files as infected. Please view \"C:\\InfectedFilesSingle.txt\" for the results", infected);
            }
            else
            {
                Console.WriteLine("Scan finished. No infected files found :)");
            }
            File.WriteAllLines(@"C:\InfectedFilesSingle.txt", infectedFiles);
    
            Console.ReadKey();
    
        }
    
    }

  6. #6
    Registered User
    Join Date
    Sep 2011
    Posts
    71
    Quote Originally Posted by Shakti View Post
    Considering he is reading EXE-files i would not advice to use StreamReader. The StreamReader class is more for reading simple text files and not binary files as the OP suggests.
    fair enough. how about passing the FileStream to System.IO.BinaryReader's constructor?

  7. #7
    Registered User
    Join Date
    Mar 2009
    Location
    england
    Posts
    209
    Hi. I can see you are converting your byte arrays to base64 strings so that you can perform comparisons. I think it would be more efficient to compare byte array against byte array so that you can skip out the conversion completely. There's no built in function to do this in C# (well, not one that I know anyway!) but you can easily make your own. Here's an example of how I would check if an array of bytes contains a desired sequence of bytes.

    Code:
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace ConsoleApplication10
    {
        class Program
        {
            static void Main(string[] args)
            {
                byte[] buf = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
                byte[] test1 = new byte[] { 2, 3, 4 };
                byte[] test2 = new byte[] { 2, 4, 6 };
    
                Console.WriteLine("buf contains test1 result: " + buf.SequenceContains(test1));
                Console.WriteLine("buf contains test2 result: " + buf.SequenceContains(test2));
                Console.Read();
            }
        }
    
        public static class Exts
        {
            public static bool SequenceContains<T>(this T[] array, T[] sequence)
            {
                for (int i = 0; i < array.Length; i++)
                {
                    if ((array.Length - i) < sequence.Length)
                        return false;
    
                    for (int x = 0; x < sequence.Length; x++)
                    {
                        if (!array[i + x].Equals(sequence[x]))
                            break;
    
                        if (x == (sequence.Length - 1))
                            return true;
                    }
                }
    
                return false;
            }
        }
    }

  8. #8
    Registered User
    Join Date
    Aug 2009
    Posts
    16
    Thank-you all for your suggestions!

    I have sorted out the issues in the program and the file read into
    Code:
    byte[] buffer = File.ReadAllBytes(currentDirectoryContents[j]);
    was from a .exe file created by pasting some HEX values into notepad and saving with the relevant extension. So when opened by the program then converted to HEX it was splitting the original HEX into two values and converting them separately....
    Silly me!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Filestream help!
    By ammochck21 in forum C++ Programming
    Replies: 5
    Last Post: 11-14-2006, 12:53 PM
  2. Visual C++ - FileStream
    By MB1 in forum C++ Programming
    Replies: 1
    Last Post: 12-09-2005, 10:19 AM
  3. Technical filestream question.
    By antex in forum C++ Programming
    Replies: 2
    Last Post: 10-26-2005, 01:11 PM
  4. filestream/operator overload help
    By confusedstudent in forum C++ Programming
    Replies: 2
    Last Post: 09-21-2004, 01:02 PM
  5. filestream- can a path name be a variable
    By stevew2607 in forum C++ Programming
    Replies: 3
    Last Post: 06-07-2002, 04:02 PM