Читаем Программирование КПК и смартфонов на .NET Compact Framework полностью

  if (MessageBox.Show("Файл уже существует, перезаписать?", this.Text,

   MessageBoxButtons.YesNo, MessageBoxIcon.Question,

   MessageBoxDefaultButton.Button2) == DialogResult.Yes)

   File.Delete(dest);

  else return;

 }

 // Перемещаем или копируем

 string s = path.Substring(0, path.Length - 1);

 switch(clipboardAction) {

 case ClipboardAction.Cut:

  File.Move(clipboardFileName, dest);

  break;

 case ClipboardAction.Copy:

  File.Copy(clipboardFileName, dest, false);

  break;

 }

 clipboardAction = ClipboardAction.None;

 clipboardFileName = string.Empty;

 fillList();

}

Перед тем как вставить файл в другую папку, нужно удостовериться, что в ней нет файла с таким именем. Если же такой файл существует, то надо предупредить пользователя и узнать, что он хочет сделать. Код для команды Вставить ярлык приведен в листинге 7.15.

Листинг 7.15

private void pasteShortcutMenuItem_Click(object sender, System.EventArgs e) {

 int i = 2;

 string s = string.Empty;

 string dest;

 while(true) {

  dest = path + "Shortcut" + s + " to " +

   Path.GetFileName(Path.GetFileNameWithoutExtension(clipboardFileName) +

   ".lnk");

  if (!File.Exists(dest)) break;

  s = " (" + i.ToString() + ")";

  i++;

 }

 StreamWriter sw = new StreamWriter(dest);

 s = clipboardFileName;

 if(s.IndexOf(" ") > 0)

  s = "\"" + s + "\"";

 s = s. Length.ToString() + "#" + s;

 sw.WriteLine(s);

 sw.Close();

 fillList();

}

В этом коде создается уникальное имя ярлыка, которое затем записывается в виде файла с добавлением. К имени ярлыка добавляется расширение .LNK.

Код для команды Переименовать приведен в листинге 7.16.

Листинг 7.16

private void renameMenuItem_Click(object sender, System.EventArgs e) {

 Cursor.Current = Cursors.WaitCursor;

 istViewItem lvi = listView.Items[listView.SelectedIndices[0]];

 bool isFolder = lvi.ImageIndex = 0;

 string s;

 if (isFolder)

  s = "папку";

 else s = "файл";

 NameForm nameForm =

  new NameForm(this, "Переименовать " + s, lvi.Text,

   new SetNameDelegate(SetRename));

 if (nameForm.ShowDialog() = DialogResult.OK) fillList();

 listView.Focus();

}

Сначала обрабатывается текущий выделенный элемент. Если пользователь выделил папку, то для формы nameForm задается соответствующий заголовок Переименовать папку. Также из этой формы передается в основную форму новое имя папки или файла с помощью метода Set Rename, как это показано в листинге 7.17.

Листинг 7.17

///

/// Метод для переименования папки или файла

///

/// Имя папки или файла

public void SetRename(string name) {

 ListViewItem lvi = listView.Items[listView.SelectedIndices[0]];

 bool isFolder = lvi.ImageIndex == 0;

 string itemName = path + lvi.Text;

 string destName =

  Path.GetDirectoryName(itemName) +

  Path.DirectorySeparatorChar.ToString() + name;

 if (isFolder)

  Directory.Move(itemName, destName);

 else

  File.Move(itemName, destName);

}

После того как будет получена информация о выделенном элементе, он переименовывается. Для реализации команды Удалить используется код, приведенный в листинге 7.18.

Листинг 7.18

private void deleteMenuItem_Click(object sender,

 System.EventArgs e) {

Перейти на страницу:

Похожие книги

C++ Primer Plus
C++ Primer Plus

C++ Primer Plus is a carefully crafted, complete tutorial on one of the most significant and widely used programming languages today. An accessible and easy-to-use self-study guide, this book is appropriate for both serious students of programming as well as developers already proficient in other languages.The sixth edition of C++ Primer Plus has been updated and expanded to cover the latest developments in C++, including a detailed look at the new C++11 standard.Author and educator Stephen Prata has created an introduction to C++ that is instructive, clear, and insightful. Fundamental programming concepts are explained along with details of the C++ language. Many short, practical examples illustrate just one or two concepts at a time, encouraging readers to master new topics by immediately putting them to use.Review questions and programming exercises at the end of each chapter help readers zero in on the most critical information and digest the most difficult concepts.In C++ Primer Plus, you'll find depth, breadth, and a variety of teaching techniques and tools to enhance your learning:• A new detailed chapter on the changes and additional capabilities introduced in the C++11 standard• Complete, integrated discussion of both basic C language and additional C++ features• Clear guidance about when and why to use a feature• Hands-on learning with concise and simple examples that develop your understanding a concept or two at a time• Hundreds of practical sample programs• Review questions and programming exercises at the end of each chapter to test your understanding• Coverage of generic C++ gives you the greatest possible flexibility• Teaches the ISO standard, including discussions of templates, the Standard Template Library, the string class, exceptions, RTTI, and namespaces

Стивен Прата

Программирование, программы, базы данных