Search code examples
c#folderbrowserdialogbinaryreader

C# - Browse Folder and Binary Reader


I am having difficulty getting Binary Reader to detect the files selected from a "Browse for Folder" dialogue. The intent is to read at "X" location within all files in a directory and save that data to a TXT file. I've tried various ways but cannot seem to get it... The line I'm having trouble with is:

BinaryReader NDSRead2 = new BinaryReader(file)

Anything I put in to replace (file) throws an error. Tried various ways with that line and elsewhere in my code but can't seem to get it. My code is listed blow.

 /// OPEN FOLDER DIALOGUE      
        FolderBrowserDialog fbd = new FolderBrowserDialog();
        fbd.Description = "Select a folder";
        fbd.ShowNewFolderButton = false;
        if (fbd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
        {
           /// THIS NEXT CHUNK OF CODE SETS UP WHERE THE TXT FILE WILL BE SAVED, IN THE SELECTED DIRECTORY.
            string brlTextLoc = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
            DirectoryInfo dir1 = new DirectoryInfo(fbd.SelectedPath);
           txtBRLSave = new System.IO.StreamWriter(fbd.SelectedPath + "BuildRomList.TXT", true);

            txtBRLSave.WriteLine("Build Rom List");
            txtBRLSave.WriteLine("Using The Rom Assistant v0.57");
            txtBRLSave.WriteLine();


          /// THE LOOP FOR EACH FILE TO BE READ IN FOLDER BEGINS.
            FileInfo[] files = dir1.GetFiles();
            System.IO.StreamWriter txtBRLSave;
            foreach (string file in Directory.EnumerateFiles(fbd.SelectedPath, "*.EXT"))
            {

                BinaryReader NDSRead2 = new BinaryReader(file);

            /// THE ISSUE I HAVE IS WITH "(FILE)" ABOVE... IT KEEPS GETTING FLAGGED IN RED NO MATTER WHAT I PUT IN THERE.

           /// BELOW CONTINUES THE BR CODE, AND TXT SAVING CODE, WHICH ISN'T NEEDED FOR THIS QUESTION AS I KNOW IT WORKS.

Solution

  • Pass the string into a stream as follows

    foreach(string file in Directory.EnumerateFiles(...
    {
        using(var stream = new FileStream(file, FileMode.Open))
        using(var NDSRead2 = new BinaryReader(stream))
        {
           // do you stuff
        }
    }