System.IO.File / FileStream

Hello everyone :) 

I'm a new guy here, and somewhat new to the .NET programming framework. 

I'm working in C# (not my languages of choice, but my company is asking me to use it to work with everyone else we just hired) 

So I guess this is my first question........could someone point me to an example of how to use the System.IO.File and System.IO.FileStream objects  

I'm trying to do one of 2 things: 

Grab a file's information and store it in a database (via the File object's static methods), or grab the file itself and store it in the database (as BLOB). 

Both of these things I don't really know how to do, but I understand what is necessary to do it from having done it in other languages........can anyone help


Answer this question

System.IO.File / FileStream

  • Mathias Raacke

    Well, leaving the database issues for some other time, here's a quick example of looping through all the files in a folder:

        private void button1_Click(object sender, System.EventArgs e)
        {
          System.IO.DirectoryInfo di = new System.IO.DirectoryInfo("C:\\");
          foreach (System.IO.FileInfo fi in di.GetFiles("*.*"))
          {
            // You could write this information to a database, as well.
            // That's a different issue, however.
            System.Diagnostics.Debug.WriteLine(fi.FullName);
            System.Diagnostics.Debug.WriteLine(fi.CreationTime);
          }

          System.IO.FileStream fs;
          foreach (System.IO.FileInfo fi in di.GetFiles("*.*"))
          {
            fs = File.OpenRead(fi.FullName);
            // You could use the fs.Read method to read the contents into a byte array,
            // and then save the contents into a database row.
            System.Diagnostics.Debug.WriteLine(fs.Length);
            fs.Close();
          }
        }

    Storing the file itself in the database as a blob is going to require fooling with byte arrays, and database-specific issues. It's basically the same issue, however--you need to loop through a folder and for each file, open a FileStream. The code shows both techniques, and there are about 17 other ways to do this, as well. That's the problem with the System.IO namespace -- there are always a lot of ways to accomplish any goal. I find myself ALWAYS going to the online help for this, and the documentation contains some simple, useful examples.

  • unreal-xan

    Thanks very much for the reply Ken!  That is going to help out a great deal!
  • System.IO.File / FileStream