From: 011netservice@gmail.com Date: 2024-03-21 Subject: OpenFileDialog.txt 歡迎來信交流, 訂購軟體需求. #### 20240321 template: private void CmdOpenFile_Click(object sender, EventArgs e) { string sInitialDirectory = _Project._PathLast; if (!Directory.Exists(sInitialDirectory)) sInitialDirectory = ZDirectory.ZGetCurrentDirectory(); string sFile = string.Empty; using (OpenFileDialog openFileDialog = new OpenFileDialog()) { openFileDialog.InitialDirectory = sInitialDirectory; //openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; //openFileDialog.FilterIndex = 2; openFileDialog.Filter = "All files (*.*)|*.*"; openFileDialog.FilterIndex = 1; openFileDialog.RestoreDirectory = true; if (openFileDialog.ShowDialog() == DialogResult.OK) sFile = openFileDialog.FileName; } if (string.IsNullOrEmpty(sFile)) return; FileInfo FileInfo1 = ZFile.ZFileInfo(sFile); txtFilename.Text = sFile; _Project._PathLast = FileInfo1.DirectoryName ?? string.Empty; } ref: https://learn.microsoft.com/en-us/dotnet/api/system.windows.forms.openfiledialog?view=windowsdesktop-8.0&devlangs=csharp&f1url=%3FappId%3DDev17IDEF1%26l%3DEN-US%26k%3Dk(System.Windows.Forms.OpenFileDialog)%3Bk(Designer_Microsoft.DotNet.DesignTools.Client.Designers.DocumentProxyDesigner)%3Bk(NonVisualSelection)%3Bk(SolutionItemsProject)%3Bk(DevLang-csharp)%26rd%3Dtrue var fileContent = string.Empty; var filePath = string.Empty; using (OpenFileDialog openFileDialog = new OpenFileDialog()) { openFileDialog.InitialDirectory = "c:\\"; openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*"; openFileDialog.FilterIndex = 2; openFileDialog.RestoreDirectory = true; if (openFileDialog.ShowDialog() == DialogResult.OK) { //Get the path of specified file filePath = openFileDialog.FileName; //Read the contents of the file into a stream var fileStream = openFileDialog.OpenFile(); using (StreamReader reader = new StreamReader(fileStream)) { fileContent = reader.ReadToEnd(); } } } MessageBox.Show(fileContent, "File Content at path: " + filePath, MessageBoxButtons.OK); #### 以下舊資料確認後移到上面 void mySelectDB() { OpenFileDialog openFileDialog1 = new OpenFileDialog(); if (String.IsNullOrEmpty(Properties.Settings.Default.PathLast)) Properties.Settings.Default.PathLast = Application.StartupPath; openFileDialog1.InitialDirectory = Properties.Settings.Default.PathLast; openFileDialog1.Filter = "db files (*.db)|*.db|All files (*.*)|*.*"; openFileDialog1.FilterIndex = 2; openFileDialog1.RestoreDirectory = true; if (openFileDialog1.ShowDialog() == DialogResult.OK) { Properties.Settings.Default.PathLast = Path.GetDirectoryName(openFileDialog1.FileName); Properties.Settings.Default.Save(); txtFile.Text = openFileDialog1.FileName; } } private void FMain_FormClosing(object sender, FormClosingEventArgs e) { myClosing(); } void myClosing() { Properties.Settings.Default.Save(); }