Private-Bookers
C# для профессионалов. Том II
вернуться

Ватсон Карли

Шрифт:

Посмотрим сначала на метод обработки событий, который вызывается, когда пользователь нажимает кнопку Delete:

protected void OnDeleteButtonClick(object sender, EventArgs e) {

 try {

string FilePath = Path.Combine(currentFolderPath, txtBoxFileName.Text);

string Query = "Really delete the file\n" + FilePath + "?";

if (MessageBox.Show(Query, "Delete File?", MessageBoxButtons.YesNo) == DialogResult.Yes) {

File.Delete(FilePath); DisplayFolderList(currentFolderPath);

}

 } catch (Exception ex) {

MessageBox.Show("Unable to delete file. The following exception" + " occured:\n" + ex.Message, "Failed");

 }

}

Код этого метода находится в блоке try в связи с очевидным риском порождения исключения, если, например, у нас нет полномочий на удаление файла или файл был перемещен другим процессом за время, прошедшее с момента вывода данных примером, и моментом, когда пользователь нажал кнопку удаления. Мы создаем путь доступа файла, чтобы удалить его из поля

CurrentParentPath
, которое будет содержать путь доступа текущей папки, и формируем текст в поле
textBoxFileName
, которое будет содержать имя файла.

Методы для перемещения и копирования файла структурированы похожим образом:

protected void OnMoveButtonClickfobject sender, EventArgs e) {

 try {

string FilePath = Path.Combine(currentFolderPath, txtBoxFileName.Text);

string Query =

"Really move the file\n" + FilePath + "\nto " + txtBoxNewPath.Text + "?";

if (MessageBox.Show(Query, "Move File?", MessageBoxButtons.YesNo) == DialogResult.Yes) {

File.Move(FilePath, txtBoxNewPath.Text);

DisplayFolderList(currentFolderPath);

}

 } catch(Exception ex) {

MessageBox.Show("Unable to move file. The following exception" + " occured: \n" + ex.Message, "Failed");

 }

}

protected void OnCopyButtonClick(object sender, EventArgs e) {

 try {

string FilePath = Path.Combine(currentFolderPath, txt.BoxFileName.Text);

string Query = "Really copy the file\n" + FilePath + "\nto " + txtBoxNewPath.Text + "?";

if (MessageBox.Show(Query, "Copy File?", MessageBoxButtons.YesNo) == DialogResult.Yes) {

File.Copy(FilePath, txtBoxNewPath.Text);

DisplayFolderList(currentFolderPath);

}

 } catch (Exception ex) {

MessageBox.Show("Unable to copy file. The following exception" + " occured:\n" + ex.Message, "Failed");

 }

}

Нам нужно также убедиться в том, что новые кнопки и текстовое поле включаются и отключаются в соответствующее время. Чтобы включить их, когда выводится содержимое файла, мы добавляем следующий код в

DisplayFileInfo
:

protected void DisplayFileInfo(string fileFullName) {

 FileInfo TheFile = new FileInfo(fileFullName);

 if (!TheFile.Exists) throw new FileNotFoundException("File not found: " + fileFullName);

 txtBoxFileName.Text = TheFile.Name;

 txtBoxCreationTime.Text = TheFile.CreationTime.ToLongTimeString;

 txtBoxLastAccessTime.Text = TheFile.LastAccessTime.ToLongDateString;

 txtBoxLastWriteTime.Text = TheFile.LastWriteTime.ToLongDateString;

 txtBoxFileSize.Text = TheFile.Length.ToString + " bytes";

 // включает кнопки перемещения, копирования и удаления

 txtBoxNewPath.Text = TheFile.FullName;

 txtBoxNewPath.Enabled = true;

 buttonCopyTo.Enabled = true;

 buttonDelete.Enabled = true;

 buttonMoveTo.Enabled = true;

}

Нам нужно также сделать одно изменение в

DisplayFolderInfo
:

protected void DisplayFolderList(string folderFullName) {

 DirectoryInfo TheFolder = new DirectoryInfo(folderFullName);

 if (!TheFolder.Exists)

  • Читать дальше
  • 1
  • ...
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • ...

Private-Bookers - русскоязычная библиотека для чтения онлайн. Здесь удобно открывать книги с телефона и ПК, возвращаться к сохраненной странице и держать любимые произведения под рукой. Материалы добавляются пользователями; если считаете, что ваши права нарушены, воспользуйтесь формой обратной связи.

Полезные ссылки

  • Моя полка