Skip to content

Instantly share code, notes, and snippets.

@d630
Created July 5, 2018 22:09
Show Gist options
  • Save d630/4c1b76f1e166ff1a0b0023ad84551cd5 to your computer and use it in GitHub Desktop.
Save d630/4c1b76f1e166ff1a0b0023ad84551cd5 to your computer and use it in GitHub Desktop.
Drag and Drop 1 (Windows Forms)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
// Label:
// Allow Drop = true
// DragEnter
// DragDrop
// Listbox:
// HorizontalScrolbar = true
// ScrollAlwaysVisible = true
namespace DragAndDrop1
{
public partial class Form1 : Form
{
public const string DIR = "C:\\test";
public Form1()
{
InitializeComponent();
}
private void label1_DragEnter(object sender, DragEventArgs e)
{
if (e.Data.GetDataPresent(DataFormats.FileDrop))
e.Effect = DragDropEffects.Copy;
}
private bool dispFile(string file)
{
try
{
richTextBox1.Text = File.ReadAllText(file);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
return true;
}
private bool copyFile(string source, string dest)
{
try
{
if (File.Exists(dest))
File.Delete(dest);
File.Copy(source, dest);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
return true;
}
private bool createDir(string dir)
{
try
{
if (!Directory.Exists(DIR))
Directory.CreateDirectory(DIR);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return false;
}
return true;
}
private void label1_DragDrop(object sender, DragEventArgs e)
{
string[] fileNames = (string[]) e.Data.GetData(DataFormats.FileDrop, false);
if (e.Data.GetDataPresent(DataFormats.FileDrop))
{
if (fileNames.Count() > 1)
{
MessageBox.Show("Nur eine Datei");
}
else
{
string file = fileNames[0];
string[] fields = file.Split('\\');
if (!createDir(DIR))
{
MessageBox.Show($"Error:Could not create dir: {DIR}");
return;
}
string path = $"{DIR}\\{fields[fields.Count() - 1]}";
label1.Text = file;
if (!dispFile(file))
{
MessageBox.Show($"Error:Could not display file: {file}");
return;
}
if (!copyFile(file, path))
{
MessageBox.Show($"Error:Could not copy file: {file} -> {path}");
return;
}
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment