C#支持文件拖拽

时间:2023-03-08 16:31:45
  1. private void listBox1_DragEnter(object sender, DragEventArgs e)
  2. {
  3. if (e.Data.GetDataPresent(DataFormats.FileDrop))
  4. {
  5. e.Effect = DragDropEffects.Copy;
  6. }
  7. else
  8. {
  9. e.Effect = DragDropEffects.None;
  10. }
  11. }
  12. private void listBox1_DragDrop(object sender, DragEventArgs e)
  13. {
  14. string[] test = (string[])e.Data.GetData(DataFormats.FileDrop, false);
  15. //MessageBox.Show(test[0].ToString());
  16. Tps1.Clear();
  17. listBox1.Items.Clear();
  18. try
  19. {
  20. if (test[0].ToString().Contains(".txt"))
  21. {
  22. StreamReader sr1 = new StreamReader(test[0].ToString(), Encoding.UTF8);
  23. string line1;
  24. while ((line1 = sr1.ReadLine()) != null)
  25. {
  26. if (line1.Trim() == "")
  27. continue;
  28. Tps1.Add(line1);
  29. listBox1.Items.Add(line1);
  30. }
  31. sr1.Close();
  32. sr1.Dispose();
  33. }
  34. }
  35. catch { MessageBox.Show("文件不能识别!"); }
  36. }