把記事本拖放至 TextBox 內並顯示資料。
using System.IO;
namespace WindowsFormsApplication1
{
public partial class DragDropText : Form
{
public DragDropText()
{
InitializeComponent();
}
private void DragDropText_Load(object sender, EventArgs e)
{
txtContent.AllowDrop = true;
}
private void txtContent_DragEnter(object sender, DragEventArgs e)
{
bool fileformatCheck = e.Data.GetDataPresent(DataFormats.FileDrop);
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
if
(
fileformatCheck == false ||
files == null || files.Length == 0 ||
Path.GetExtension(files[0]).ToUpperInvariant() != ".TXT"
)
{
e.Effect = DragDropEffects.None;
}
else
{
e.Effect = DragDropEffects.Copy;
}
}
private void txtContent_DragDrop(object sender, DragEventArgs e)
{
string[] files = (string[])e.Data.GetData(DataFormats.FileDrop);
string filepath = files[0];
FileStream fs = new FileStream(filepath, FileMode.Open, FileAccess.Read);
StreamReader sr = new StreamReader(fs, Encoding.Default);
txtContent.Text = sr.ReadToEnd();
}
}
}
文字檔案(預設編碼為 ANSI)編碼格式與 Stream 必須一致才能正確顯示文字,因此產生 StreamReader 時,指定 Encoding.Default 來避免亂碼產生。
沒有留言:
張貼留言