У меня есть две кнопки в форме Windows, одна называется Browse
, а другая называется Change Location
.
Я хотел бы иметь возможность установить значение InitialDirectory
для каждой из этих кнопок.
Причина этого в том, что кнопка Browse
открывает изображения для отображения на экране, а кнопка Change Location
сохраняет текстовый файл в выбранном месте. Я хочу, чтобы эти папки были разными.
Я предоставил код ниже для того, что у меня есть до сих пор:
//Code for the browse button
private void browseButton_Click(object sender, EventArgs e)
{
using (OpenFileDialog openFileDialog1 = new OpenFileDialog())
{
openFileDialog1.Title = "Select Image Files To Be Displayed";
openFileDialog1.InitialDirectory = @"..\..\pigeonImages\";
// Set filter options and filter index.
openFileDialog1.Filter = "Image Files|*.png;*.jpeg;*.gif|All Files|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.FileName = String.Empty;
//Allow for multiple files to be selected
openFileDialog1.Multiselect = true;
// Call the ShowDialog method to show the dialog box.
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
//Create a stream which points to the open file
Stream openFileStream = openFileDialog1.OpenFile();
//Create a reader
StreamReader reader = new StreamReader(openFileStream);
//Read the contents of the stream
string shortenedFilenames = String.Empty;
StringBuilder totalFiles = new StringBuilder();
//to get just one filename use openDialog1.FileName
//to get multiple filenames use openDialog1.FileNames
foreach(string file in openFileDialog1.FileNames)
{
shortenedFilenames = file.Substring(openFileDialog1.FileName.LastIndexOf(@"\") + 1);
totalFiles.Append(shortenedFilenames).Append(", ");
}
string totalFilesResult = totalFiles.ToString();
totalFilesResult = totalFilesResult.TrimEnd(' ');
totalFilesResult = totalFilesResult.TrimEnd(',');
tbResults.Text = totalFilesResult;
System.Diagnostics.Debug.WriteLine("fileStream -> " + totalFilesResult);
//Close the reader
reader.Close();
}
}
}
//Code for the Change Location button
private void saveLocationButton_Click(object sender, EventArgs e)
{
using (SaveFileDialog saveTextDialog = new SaveFileDialog())
{
saveTextDialog.Title = "Save File In Correct Folder!";
saveTextDialog.InitialDirectory = @"..\..\testScores\";
tbSaveLocation.BackColor = Color.White;
tbSaveLocation.ForeColor = Color.Black;
saveTextDialog.Filter = "Text Files | *.txt";
saveTextDialog.DefaultExt = "txt";
saveResult = saveTextDialog.ShowDialog();
if (saveResult == DialogResult.OK)
{
Stream saveFileStream = saveTextDialog.OpenFile();
using (StreamWriter writer = new StreamWriter(saveFileStream))
{
writer.Write("");
writer.Flush();
//writer.Close();
}
}
tbSaveLocation.Text = String.Format("testScores/{0}/{0}.txt", birdIdString);
}
}
Есть ли что-то, что мне здесь не хватает?
Я установил другое значение InitialDirectory
в каждом методе. Я также использовал строку без @symbol и изменил \ на /, но это все равно не работает.
Кажется, что какую бы кнопку я ни нажимал, всегда отображается папка pigeonImages
. Я также пробовал вариант RestoreDirectory
в каждом методе, в обоих методах и ни в одном методе, но это тоже не работает.
Заранее спасибо.
Когда я отправляю openFileDialog1.InitialDirectory
на консоль, я получаю это как вывод:
C:\path\to\my\program\here\bin\Debug\..\..\pigeonImages\
Я всегда думал, что ввод ..\
поднимет вас на уровень папки. Я привык писать код на Mac, есть ли в Windows другой способ перехода к папке?
ShowDialog
и добавьте контрольное выражениеDirectory.Exists(@"..\..\pigeonImages")
. А также проверьте, установил ли диалог начальный путь... - person BrunoLM   schedule 30.01.2014