Csharp/C Sharp/GUI Windows Form/Open File Dialog

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Call ShowDialog() to display an OpenFileDialog

<source lang="csharp"> using System; using System.Windows.Forms; class MainClass {

   static void Main(string[] args) {
       OpenFileDialog dlg = new OpenFileDialog();
       if (dlg.ShowDialog() == DialogResult.OK) {
           Console.WriteLine(dlg.FileName);
       }
   }

}

</source>


Demonstrates using an OpenFileDialog to prompt for a file name, and to open a file

<source lang="csharp"> /* C# Programming Tips & Techniques by Charles Wright, Kris Jamsa Publisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794

  • /

// ReadIn.cs -- Demonstrates using an OpenFileDialog to prompt for a // file name, and to open a file // // Compile this program with the following command line: // C:>csc ReadIn.cs using System; using System.IO; using System.Windows.Forms; namespace nsStreams {

   public class ReadIn
   {
       [STAThread]
       static public void Main (string [] args)
       {
           OpenFileDialog fileOpen = new OpenFileDialog ();
           if (args.Length == 0)
           {
               fileOpen.InitialDirectory = ".\\";
               fileOpen.Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*";
               fileOpen.FilterIndex = 0;
               fileOpen.RestoreDirectory = false; //true;

// if (fileOpen.ShowDialog () == DialogResult.Cancel)

               if (fileOpen.ShowDialog () != DialogResult.OK)
               {
                   return;
               }
           }
           else
           {
               fileOpen.FileName = args[0];
           }
           Stream strm;
           StreamReader reader;
           try
           {
               strm = fileOpen.OpenFile ();
               reader = new StreamReader (strm);
           }
           catch (Exception e)
           {
               string Message = e.Message + "\n\nCannot open "
                                + fileOpen.FileName;
               MessageBox.Show (Message, "Open error",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Error);
               return;
           }
           Console.Write (reader.ReadToEnd ());
           reader.Close ();
           strm.Close ();
       }
   }

}


      </source>


FileOk Action

<source lang="csharp"> using System; using System.IO; using System.Windows.Forms; class FileDialogApp {

   private static OpenFileDialog ofd;
   static void Main(string[] args) {
       ofd = new OpenFileDialog();
       string s = Path.GetDirectoryName(Path.GetDirectoryName(Directory.GetCurrentDirectory()));
       ofd.InitialDirectory = s;
       ofd.FileOk += new System.ruponentModel.CancelEventHandler(ofd_OK);
       ofd.ShowDialog();
   }
   public static void ofd_OK(object sender,
       System.ruponentModel.CancelEventArgs e) {
       StreamReader sr = new StreamReader(ofd.FileName);
       string s;
       while ((s = sr.ReadLine()) != null) {
           Console.WriteLine(s);
       }
       sr.Close();
   }

}

</source>


Open File Dialog with file types

<source lang="csharp"> /* C# Programming Tips & Techniques by Charles Wright, Kris Jamsa Publisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794

  • /

namespace nsClassLib {

   using System;
   using System.IO;
   using System.Windows.Forms;
   
   public class clsMainOpenFileDialog
   {
       [STAThread]
       static public void Main ()
       {
           OpenFileDialog ofn = new OpenFileDialog ();
           ofn.Filter = "C Sharp Files (*.cs)|*.cs|Text Files (*.txt)|*.txt";
           ofn.Title = "Type File";
           while (true)
           {
               if (ofn.ShowDialog () == DialogResult.Cancel)
                   return;
               FileStream strm;
               try
               {
                   strm = new FileStream (ofn.FileName, FileMode.Open, FileAccess.Read);
                   StreamReader rdr = new StreamReader (strm);
                   while (rdr.Peek() >= 0)
                   {
                        string str = rdr.ReadLine ();
                        Console.WriteLine (str);
                   }
               }
               catch (Exception)
               {
                   MessageBox.Show ("Error opening file", "File Error",
                                    MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
               }
               ofn.Title = "Next File to Type";
           }
       }
   }

}


      </source>


Set Filter

<source lang="csharp"> using System; using System.Windows.Forms; class MainClass {

   static void Main(string[] args) {
       OpenFileDialog dlg = new OpenFileDialog();
       dlg.Filter = "Rich Text Files (*.rtf)|*.RTF|" +
         "All files (*.*)|*.*";
       if (dlg.ShowDialog() == DialogResult.OK) {
           Console.WriteLine(dlg.FileName);
       }
   }

}

</source>


Set InitialDirectory

<source lang="csharp"> using System; using System.Windows.Forms; class MainClass {

   static void Main(string[] args) {
       OpenFileDialog dlg = new OpenFileDialog();
       dlg.InitialDirectory = Application.StartupPath;
       if (dlg.ShowDialog() == DialogResult.OK) {
           Console.WriteLine(dlg.FileName);
       }
   }

}

</source>


shows browsing for a file

<source lang="csharp"> /* Mastering Visual C# .NET by Jason Price, Mike Gunderloy Publisher: Sybex; ISBN: 0782129110

  • /
/*
 Example15_1.cs shows browsing for a file
  • /

using System; using System.Windows.Forms; public class Example15_1 {

 [STAThread]
 public static void Main() {
   // create and show an open file dialog
 OpenFileDialog dlgOpen = new OpenFileDialog();
 if (dlgOpen.ShowDialog() == DialogResult.OK)
   {
   Console.Write(dlgOpen.FileName);
   }
 }

}


      </source>


shows browsing for a set of files

<source lang="csharp"> /* Mastering Visual C# .NET by Jason Price, Mike Gunderloy Publisher: Sybex; ISBN: 0782129110

  • /
/*
 Example15_2.cs shows browsing for a set of files
  • /

using System; using System.Windows.Forms; public class Example15_2 {

   [STAThread]
 public static void Main() 
 {
   // create an open file dialog
   OpenFileDialog dlgOpen = new OpenFileDialog();
   
   // set properties for the dialog
   dlgOpen.Title = "Select one or more files";
   dlgOpen.ShowReadOnly = true;
   dlgOpen.Multiselect = true;
   // display the dialog and return results
   if (dlgOpen.ShowDialog() == DialogResult.OK)
   {
     foreach (string s in dlgOpen.FileNames)
       Console.WriteLine(s);
   }
 }

}

      </source>


Show the use of some of the OpenFile dialog box

<source lang="csharp"> /* C# Programming Tips & Techniques by Charles Wright, Kris Jamsa Publisher: Osborne/McGraw-Hill (December 28, 2001) ISBN: 0072193794

  • /

// DlgSamp.cs -- Show the use of some of the OpenFile dialog box. // // Compile this program with the following command line: // C:>csc DlgSamp.cs using System; using System.Windows.Forms; using System.ruponentModel; public class clsMainOpenFile {

   [STAThread]
   static public void Main ()
   {

// Create the dialog box object.

       OpenFileDialog ofd = new OpenFileDialog ();

// Allow multiple file selection.

       ofd.Multiselect = true;

// Set the text for the title bar.

       ofd.Title = "Concatenate files";

// Do not verify that the file exists.

       ofd.CheckFileExists = false;

// Do verify that the path exists.

       ofd.CheckPathExists = true;

// Add a default extension if the user does not type one.

       ofd.AddExtension = true;

// Set the default extension.

       ofd.DefaultExt = "txt";

// Show the read-only box.

       ofd.ShowReadOnly = true;

// Show the Help button.

       ofd.ShowHelp = true;

// Call this method when the user clicks the OK (Open) button.

       ofd.FileOk += new CancelEventHandler (CancelOpenFile);

// Call this method when the user clicks the Help button.

       ofd.HelpRequest += new EventHandler (ShowOpenHelp);

// Show the dialog box.

       if (ofd.ShowDialog () == DialogResult.Cancel)
           return;

// Display a list of the selected files.

       foreach (string str in ofd.FileNames)
           Console.WriteLine (str);
   }

// Delegate called when the user clicks the OK (Open) button

   static private void CancelOpenFile (object sender, CancelEventArgs e)
   {

// Cast the object to an OpenFileDialog object.

       OpenFileDialog dlg = (OpenFileDialog) sender;

// Show the selected files.

       Console.WriteLine ("The selected file are:");
       foreach (string str in dlg.FileNames)
           Console.WriteLine ("\t" + str);

// Ask whether to cancel the close event.

       Console.Write ("\r\nCancel event? [y/n]: ");
       string reply = Console.ReadLine ();
       if (reply[0] == "y")
           e.Cancel = true;
   }

// Delegate called when the user clicks the Help button.

   static private void ShowOpenHelp (object sender, EventArgs e)
   {
       Console.WriteLine ("Open your help file to the File Open topic here.");
   }

}

      </source>