using System; using System.IO; using System.Linq; using System.Text; using…
- User
using System; using System.IO; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Media; using System.Windows.Media.Animation;
namespace DragDropTextFilesApp { public partial class MainWindow : Window { private readonly SolidColorBrush NormalBorderBrush = new SolidColorBrush(Color.FromRgb(153, 153, 153)); // #999999 private readonly SolidColorBrush HighlightBorderBrush = new SolidColorBrush(Color.FromRgb(0, 122, 204)); // 蓝色高亮
public MainWindow() { InitializeComponent(); StatusText.Text = "请将包含文本文档的文件夹拖放到上方区域。"; DropArea.BorderBrush = NormalBorderBrush; } private void DropArea_DragOver(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop, true)) { string[] paths = (string[])e.Data.GetData(DataFormats.FileDrop, true); if (paths.Length > 0 && Directory.Exists(paths[0])) { e.Effects = DragDropEffects.Copy; AnimateBorderColor(DropArea, HighlightBorderBrush); } else { e.Effects = DragDropEffects.None; AnimateBorderColor(DropArea, NormalBorderBrush); } } else { e.Effects = DragDropEffects.None; AnimateBorderColor(DropArea, NormalBorderBrush); } e.Handled = true; } private void DropArea_Drop(object sender, DragEventArgs e) { AnimateBorderColor(DropArea, NormalBorderBrush); StatusText.Text = "正在处理文件..."; ContentRichTextBox.Visibility = Visibility.Collapsed; try { if (e.Data.GetDataPresent(DataFormats.FileDrop, true)) { string[] paths = (string[])e.Data.GetData(DataFormats.FileDrop, true); if (paths.Length > 0 && Directory.Exists(paths[0])) { string folderPath = paths[0]; // 获取所有的 .txt 文件(不包括子文件夹) string[] txtFiles = Directory.GetFiles(folderPath, "*.txt", SearchOption.TopDirectoryOnly); if (txtFiles.Length == 0) { MessageBox.Show("所选文件夹中没有找到 .txt 文档。", "提示", MessageBoxButton.OK, MessageBoxImage.Information); StatusText.Text = "未找到 .txt 文件。"; return; } StringBuilder sb = new StringBuilder(); foreach (var file in txtFiles.OrderBy(f => f)) { sb.AppendLine($"--- 文件: {System.IO.Path.GetFileName(file)} ---"); sb.AppendLine(File.ReadAllText(file)); sb.AppendLine(); } // 使用 RichTextBox 显示内容 ContentRichTextBox.Document.Blocks.Clear(); ContentRichTextBox.Document.Blocks.Add(new Paragraph(new Run(sb.ToString()))); ContentRichTextBox.Visibility = Visibility.Visible; StatusText.Text = $"成功加载 {txtFiles.Length} 个文件。"; } else { MessageBox.Show("请拖放一个有效的文件夹。", "错误", MessageBoxButton.OK, MessageBoxImage.Error); StatusText.Text = "无效的拖放内容。"; } } } catch (Exception ex) { MessageBox.Show($"处理文件时发生错误:\n{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error); StatusText.Text = "发生错误。"; } } /// <summary> /// 动画切换边框颜色 /// </summary> /// <param name="border">目标边框</param> /// <param name="toColor">目标颜色</param> private void AnimateBorderColor(Border border, SolidColorBrush toColor) { ColorAnimation colorAnimation = new ColorAnimation { To = toColor.Color, Duration = TimeSpan.FromMilliseconds(200) }; border.BorderBrush.BeginAnimation(SolidColorBrush.ColorProperty, colorAnimation); } }}<Window x:Class="DragDropTextFilesApp.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:DragDropTextFilesApp" Title="文本文件合并器" Height="600" Width="900" Background="#1E1E1E" WindowStartupLocation="CenterScreen" AllowsTransparency="False" ResizeMode="CanResize"> <Grid.RowDefinitions> </Grid.RowDefinitions>
<!-- 拖放区域及选择文件夹按钮 --> <Border x:Name="DropArea" Grid.Row="0" BorderBrush="#4D4D4D" <!-- 边框颜色 --> BorderThickness="2" CornerRadius="10" Background="#2D2D30" <!-- 拖放区域背景 --> AllowDrop="True" DragOver="DropArea_DragOver" Drop="DropArea_Drop" Padding="20" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> <Grid> <TextBlock Text="将包含文本文档的文件夹或多个文本文件拖放到此区域" FontSize="18" Foreground="White" HorizontalAlignment="Center" VerticalAlignment="Center" TextWrapping="Wrap" TextAlignment="Center"/> </Grid> </Border> <!-- 显示内容区域 --> <RichTextBox x:Name="ContentRichTextBox" Grid.Row="1" Margin="0,20,0,20" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" IsReadOnly="True" FontFamily="Consolas" FontSize="14" Background="#1E1E1E" <!-- RichTextBox 背景 --> Foreground="White" <!-- RichTextBox 字体颜色 --> SelectionBrush="LightBlue" <!-- 选择文本时的背景色 --> Visibility="Collapsed"> </RichTextBox> <!-- 状态栏 --> <StatusBar Grid.Row="2" Background="#2D2D30"> <StatusBarItem> <TextBlock x:Name="StatusText" Text="准备就绪" Foreground="White" /> </StatusBarItem> </StatusBar> </Grid>NET 4.8 FRAM WORK 现在实现了拖入文件夹 但是不能拖入文本文件 我想的是 可以一次性拖入鼠标选中的不同文件夹 文本文件 然后再UI 顺序保留内容 并且可以复制他们
- Assistant
要实现一次性拖入多个文件夹和/或多个文本文件,并在UI中按拖放顺序保留内容,同时确保内容可以复制,您需要修改现有代码以处理多种拖放情形。以下是详细的步骤和代码修改建议:
-
修改
DragOver处理程序:- 允许拖放多个项目(文件或文件夹)。
- 校验所有拖放项是否为文件夹或
.txt文件。 - 如果其中包含无效项,则不允许拖放。
-
修改
Drop处理程序:- 遍历所有拖放项。
- 对于每个拖放项,如果是文件夹,则获取其内部的
.txt文件;如果是.txt文件,则直接处理。 - 按拖放顺序将内容添加到
RichTextBox中。
-
优化 UI 显示:
- 保持
RichTextBox可见,以便用户可以复制内容。 - 按照拖放顺序清晰地显示每个文件的内容。
- 保持
以下是修改后的完整代码:
MainWindow.xaml
无需对 XAML 进行重大修改,但确保
RichTextBox和拖放区域的命名正确。以下是优化后的 XAML:<Window x:Class="DragDropTextFilesApp.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:DragDropTextFilesApp" Title="文本文件合并器" Height="600" Width="900" Background="#1E1E1E" <!-- 深色背景 --> WindowStartupLocation="CenterScreen" AllowsTransparency="False" ResizeMode="CanResize"> <Grid Margin="20"> <Grid.RowDefinitions> <!-- 拖放区域 --> <RowDefinition Height="3*" /> <!-- 显示内容区域 --> <RowDefinition Height="7*" /> <!-- 状态栏 --> <RowDefinition Height="Auto" /> </Grid.RowDefinitions> <!-- 拖放区域及选择文件夹按钮 --> <Border x:Name="DropArea" Grid.Row="0" BorderBrush="#4D4D4D" <!-- 边框颜色 --> BorderThickness="2" CornerRadius="10" Background="#2D2D30" <!-- 拖放区域背景 --> AllowDrop="True" DragOver="DropArea_DragOver" Drop="DropArea_Drop" Padding="20" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"> <Grid> <TextBlock Text="将包含文本文档的文件夹或多个文本文件拖放到此区域" FontSize="18" Foreground="White" HorizontalAlignment="Center" VerticalAlignment="Center" TextWrapping="Wrap" TextAlignment="Center"/> </Grid> </Border> <!-- 显示内容区域 --> <RichTextBox x:Name="ContentRichTextBox" Grid.Row="1" Margin="0,20,0,20" VerticalScrollBarVisibility="Auto" HorizontalScrollBarVisibility="Auto" IsReadOnly="True" FontFamily="Consolas" FontSize="14" Background="#1E1E1E" <!-- RichTextBox 背景 --> Foreground="White" <!-- RichTextBox 字体颜色 --> SelectionBrush="LightBlue" <!-- 选择文本时的背景色 --> Visibility="Collapsed"> </RichTextBox> <!-- 状态栏 --> <StatusBar Grid.Row="2" Background="#2D2D30"> <StatusBarItem> <TextBlock x:Name="StatusText" Text="准备就绪" Foreground="White" /> </StatusBarItem> </StatusBar> </Grid> </Window>MainWindow.xaml.cs
以下是修改和优化后的代码,支持同时拖入多个文件夹和/或多个
.txt文件:using System; using System.IO; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Documents; using System.Windows.Media; using System.Windows.Media.Animation; namespace DragDropTextFilesApp { public partial class MainWindow : Window { private readonly SolidColorBrush NormalBorderBrush = new SolidColorBrush(Color.FromRgb(153, 153, 153)); // #999999 private readonly SolidColorBrush HighlightBorderBrush = new SolidColorBrush(Color.FromRgb(0, 122, 204)); // 蓝色高亮 public MainWindow() { InitializeComponent(); StatusText.Text = "请将包含文本文档的文件夹或多个 .txt 文件拖放到上方区域。"; DropArea.BorderBrush = NormalBorderBrush; } private void DropArea_DragOver(object sender, DragEventArgs e) { if (e.Data.GetDataPresent(DataFormats.FileDrop, true)) { string[] paths = (string[])e.Data.GetData(DataFormats.FileDrop, true); if (paths.Length > 0 && paths.All(path => Directory.Exists(path) || IsTextFile(path))) { e.Effects = DragDropEffects.Copy; AnimateBorderColor(DropArea, HighlightBorderBrush); } else { e.Effects = DragDropEffects.None; AnimateBorderColor(DropArea, NormalBorderBrush); } } else { e.Effects = DragDropEffects.None; AnimateBorderColor(DropArea, NormalBorderBrush); } e.Handled = true; } private void DropArea_Drop(object sender, DragEventArgs e) { AnimateBorderColor(DropArea, NormalBorderBrush); StatusText.Text = "正在处理文件..."; ContentRichTextBox.Visibility = Visibility.Collapsed; try { if (e.Data.GetDataPresent(DataFormats.FileDrop, true)) { string[] paths = (string[])e.Data.GetData(DataFormats.FileDrop, true); if (paths.Length == 0) { StatusText.Text = "未检测到任何文件或文件夹。"; return; } // 验证所有拖放项是否有效 if (!paths.All(path => Directory.Exists(path) || IsTextFile(path))) { MessageBox.Show("拖放的内容必须是文件夹或 .txt 文件。", "错误", MessageBoxButton.OK, MessageBoxImage.Error); StatusText.Text = "无效的拖放内容。"; return; } // 收集所有要处理的 .txt 文件 var allTxtFiles = new System.Collections.Generic.List<string>(); foreach (var path in paths) { if (Directory.Exists(path)) { // 获取文件夹中的所有 .txt 文件(不包括子文件夹) var txtFilesInDir = Directory.GetFiles(path, "*.txt", SearchOption.TopDirectoryOnly); allTxtFiles.AddRange(txtFilesInDir); } else if (IsTextFile(path)) { allTxtFiles.Add(path); } } if (allTxtFiles.Count == 0) { MessageBox.Show("所选内容中没有找到 .txt 文档。", "提示", MessageBoxButton.OK, MessageBoxImage.Information); StatusText.Text = "未找到 .txt 文件。"; return; } // 按拖放顺序排序文件 var orderedFiles = allTxtFiles.OrderBy(f => GetDropOrder(paths, f)).ToList(); StringBuilder sb = new StringBuilder(); foreach (var file in orderedFiles.Distinct()) { sb.AppendLine($"--- 文件: {System.IO.Path.GetFileName(file)} ---"); sb.AppendLine(File.ReadAllText(file)); sb.AppendLine(); } // 使用 RichTextBox 显示内容 ContentRichTextBox.Document.Blocks.Clear(); ContentRichTextBox.Document.Blocks.Add(new Paragraph(new Run(sb.ToString()))); ContentRichTextBox.Visibility = Visibility.Visible; StatusText.Text = $"成功加载 {allTxtFiles.Count} 个文件。"; } } catch (Exception ex) { MessageBox.Show($"处理文件时发生错误:\n{ex.Message}", "错误", MessageBoxButton.OK, MessageBoxImage.Error); StatusText.Text = "发生错误。"; } } /// <summary> /// 检查文件是否为 .txt 文件 /// </summary> /// <param name="path">文件路径</param> /// <returns>是否为 .txt 文件</returns> private bool IsTextFile(string path) { return File.Exists(path) && string.Equals(Path.GetExtension(path), ".txt", StringComparison.OrdinalIgnoreCase); } /// <summary> /// 动画切换边框颜色 /// </summary> /// <param name="border">目标边框</param> /// <param name="toColor">目标颜色</param> private void AnimateBorderColor(Border border, SolidColorBrush toColor) { ColorAnimation colorAnimation = new ColorAnimation { To = toColor.Color, Duration = TimeSpan.FromMilliseconds(200) }; border.BorderBrush.BeginAnimation(SolidColorBrush.ColorProperty, colorAnimation); } /// <summary> /// 获取文件在拖放项中的顺序 /// </summary> /// <param name="paths">拖放的路径数组</param> /// <param name="filePath">文件路径</param> /// <returns>文件的拖放顺序索引</returns> private int GetDropOrder(string[] paths, string filePath) { for (int i = 0; i < paths.Length; i++) { if (filePath.StartsWith(paths[i], StringComparison.OrdinalIgnoreCase)) { return i; } } return paths.Length; // 默认放在最后 } } }关键改动详解
-
DragOver方法:- 使用
paths.All(path => Directory.Exists(path) || IsTextFile(path))来确保所有拖放项都是有效的(即,文件夹或.txt文件)。 - 如果所有项都有效,则允许拖放并高亮显示边框;否则,不允许拖放并恢复正常边框颜色。
- 使用
-
Drop方法:- 遍历所有拖放项,分别处理文件夹和
.txt文件。 - 使用
List<string>收集所有.txt文件路径,避免重复。 - 添加
GetDropOrder方法以保持文件按拖放顺序排序。
- 遍历所有拖放项,分别处理文件夹和
-
新添加的方法:
IsTextFile: 判断给定路径是否为.txt文件。GetDropOrder: 确保文件按拖放顺序添加到RichTextBox中。
-
UI 更新:
- 处理完成后,显示所有内容并更新状态栏。
- 如果未找到任何
.txt文件,则提示用户。
-
错误处理:
- 添加了更多的错误检查和用户提示,确保用户体验更佳。
测试和验证
在完成上述修改后,建议进行以下测试:
-
拖入多个文件夹:
- 确认所有文件夹中的
.txt文件被正确加载并显示。 - 检查顺序是否与拖放顺序一致。
- 确认所有文件夹中的
-
拖入多个
.txt文件:- 确认所有文件被正确加载并显示。
- 检查顺序是否与拖放顺序一致。
-
混合拖入文件夹和
.txt文件:- 确认所有文件和文件夹中的
.txt文件被正确加载。 - 检查顺序是否与拖放顺序一致。
- 确认所有文件和文件夹中的
-
尝试拖入无效文件:
- 确认应用程序拒绝拖放并提示错误信息。
通过以上改动,您的应用程序将能够更灵活地处理用户的拖放操作,同时提供良好的用户体验。
-