首页 > 编程语言 >使用C# WPF写简单的桌面应用程序

使用C# WPF写简单的桌面应用程序

时间:2024-02-23 12:46:25浏览次数:26  
标签:string C# Text resultArea 应用程序 folderName directoryInfo newFileName WPF

前言

微软真是永远滴神,Visual Studio不愧是宇宙第一IDE,C#相比Java真的是语法简洁优雅

案例

实现了一个快速重命名的小程序,打包完以后的exe不到200KB,比Java轻的不是一点半点,而且在windows上执行效率很高,直接就可以在windows双击运行

mainwindow

20232024

创建项目

Visual Studio 安装

Visual Studio 安装

选择WPF

选择WPF

选择.Net6.0

选择.Net6.0

代码

FolderProfile.pubxml

<?xml version="1.0" encoding="utf-8"?>
<!--
https://go.microsoft.com/fwlink/?LinkID=208121.
-->
<Project>
  <PropertyGroup>
    <Configuration>Release</Configuration>
    <Platform>Any CPU</Platform>
    <PublishDir>bin\Release\net6.0-windows\publish\</PublishDir>
    <PublishProtocol>FileSystem</PublishProtocol>
    <_TargetId>Folder</_TargetId>
	<OutputType>WinExe</OutputType>
	<PublishSingleFile>true</PublishSingleFile>
	<SelfContained>false</SelfContained>
	<RuntimeIdentifier>win-x64</RuntimeIdentifier>
	<TargetFramework>net6.0-windows</TargetFramework>
	<PublishReadyToRun>true</PublishReadyToRun>
  </PropertyGroup>
</Project>

MainWindow.xaml

<Window x:Class="ChangeViedoEnableDir.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:ChangeViedoEnableDir"
        mc:Ignorable="d"
        Title="MainWindow" Height="400" Width="800">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="9*"/>
            <ColumnDefinition Width="151*"/>
        </Grid.ColumnDefinitions>
        <Label Content="要启用的文件夹" HorizontalAlignment="Left" Margin="0,46,0,0" VerticalAlignment="Top" Height="52" Width="190" FontSize="24" Grid.Column="1"/>
        <TextBox x:Name="enableDirName" HorizontalAlignment="Left" Margin="194,51,0,0" TextWrapping="Wrap" VerticalAlignment="Top" Width="150" Height="42" FontSize="24" Grid.Column="1"/>
        <Button Content="执行" IsDefault="True" HorizontalAlignment="Left" Margin="374,51,0,0" VerticalAlignment="Top" Height="40" Width="105" FontSize="24" Click="Button_Click" Grid.Column="1"/>
        <Border BorderThickness="1" BorderBrush="Black" Margin="11,103,88,70" Grid.Column="1">
            <TextBlock x:Name="resultArea" HorizontalAlignment="Left" TextWrapping="Wrap" VerticalAlignment="Top" ><Run Language="zh-cn"/></TextBlock>
        </Border>
    </Grid>
</Window>

MainWindow.xaml.cs

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Windows;

namespace ChangeViedoEnableDir
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();
        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {

            Stopwatch stopwatch = new ();
            stopwatch.Start();


            resultArea.Text = "";
            // 获取当前盘符
            // 存储所有文件夹的列表
            List<DirectoryInfo> directoryList = new();

            try
            {
                string currentDrive = System.IO.Path.GetPathRoot(Environment.CurrentDirectory) ?? string.Empty;
                if (currentDrive == string.Empty)
                {
                    Debug.WriteLine("null currentDrive");
                    return;
                }
                else
                {
                    Debug.WriteLine($"currentDrive: {currentDrive}");
                    resultArea.Text += $"currentDrive: {currentDrive} \n";
                }

                // 遍历当前盘符根目录下的所有文件夹
                resultArea.Text += "读取到文件夹 ";
                foreach (string folderPath in Directory.GetDirectories(currentDrive))
                {
                    DirectoryInfo directoryInfo = new (folderPath);
                    string folderName = directoryInfo.Name;
                    int dirInt = 0;
                    bool isIntDir = int.TryParse(folderName, out dirInt);
                    if (isIntDir && dirInt>0)
                    {
                        directoryList.Add(directoryInfo);
                        Debug.WriteLine(folderName);
                        resultArea.Text += $" {folderName}";
                    }
                }
                resultArea.Text += "\n";

                string enableDir = enableDirName.Text;
                Debug.WriteLine($"启用文件夹: {enableDir}");
                resultArea.Text += $"启用文件夹: {enableDir} \n";

                bool checkEnableDirExist = false;
                foreach (DirectoryInfo directoryInfo in directoryList)
                {
                    string folderName = directoryInfo.Name;
                    if (folderName == enableDir)
                    {
                        checkEnableDirExist = true; 
                        break;
                    }
                }
                if (checkEnableDirExist == false)
                {
                    resultArea.Text += $" {enableDir} 不存在 \n";
                    return;
                }




                foreach (DirectoryInfo directoryInfo in directoryList)
                {
                    int renameCount = 0;
                    string folderName = directoryInfo.Name;
                    if (folderName == enableDir)
                    {
                        FileInfo[] fileInfos = directoryInfo.GetFiles();
                        foreach (FileInfo fileInfo in fileInfos)
                        {
                            string name = fileInfo.Name;
                            if (name.EndsWith(".mp4.netbak"))
                            {
                                string newFileName = name.Remove(name.LastIndexOf(".netbak"));
                                Debug.WriteLine($"newFileName: {newFileName} ");
                                string newFilePath = Path.Combine(directoryInfo.FullName, newFileName);
                                File.Move(fileInfo.FullName, newFilePath);
                                renameCount++;
                            }
                        }
                        resultArea.Text += $"{folderName} 后缀添加netbak {renameCount} 个 \n";
                    }
                    else
                    {
                        FileInfo[] fileInfos = directoryInfo.GetFiles();
                        foreach (FileInfo fileInfo in fileInfos)
                        {
                            string name = fileInfo.Name;
                            if (name.EndsWith(".mp4"))
                            {
                                string newFileName = name + ".netbak";
                                Debug.WriteLine($"newFileName: {newFileName} ");
                                string newFilePath = Path.Combine(directoryInfo.FullName, newFileName);
                                File.Move(fileInfo.FullName, newFilePath);
                                renameCount++;
                            }
                        }
                        resultArea.Text += $"{folderName} 后缀去掉netbak {renameCount} 个 \n";
                    }


                }

            }
            catch (Exception ex)
            {
                Debug.WriteLine("发生异常: " + ex.Message);
                resultArea.Text += $"发生异常: {ex.Message} \n";
            }

            stopwatch.Stop();
            TimeSpan elapsed = stopwatch.Elapsed;
            resultArea.Text += $"全过程耗时: {elapsed.TotalMilliseconds} 毫秒 \n";
        }
    }
}

标签:string,C#,Text,resultArea,应用程序,folderName,directoryInfo,newFileName,WPF
From: https://www.cnblogs.com/lazykingloveu/p/18029248

相关文章

  • [GIT] 修改之前的commit提交的作者信息和邮箱信息 [转]
    1总体思路更改之前提交的作者信息和邮箱信息需要进行两步操作。首先,使用gitfilter-branch命令进行历史重写然后,使用gitpush--force将更改推送到远程仓库。Step1使用gitfilter-branch进行历史重写在终端或命令行中执行以下命令:gitfilter-branch--env-filte......
  • winSCP 默认不支持root用户登录
    1.首先确保有对root用户进行密码设置:sudopasswdroot2. 修改etc/ssh/sshd_config文件:注:不能直接登录可以先用普通用户登录,然后再将用户切换为root用户(实际上我也是这么做的)vim/etc/ssh/sshd_config3.确定主要配置:PermitRootLoginyesStrictModesyes4.重启ssh服......
  • 3、remi--CheckBox
    源码链接:remi.gui.CheckBox  后面不不再在文中复述本地安装包的源码,本地源码请自行查看,文中只提供上述链接 复选框小部件:  官网文档说的是:  复选框小部件作为数值输入字段很有用,实现了onchange事件 小部件使用测试:  checkboxLab.pyimportremi.guiasguifr......
  • CreateHolesInImage说明文档-对于遥感影像的空洞创建多边形矢量数据
    提取遥感影像的空洞地理处理工具箱特点:通用地理处理工具,支持任何遥感影像,包括无人机,卫星遥感,普通图片和gdb,mdb数据库等。速度快,极致效率,效率高,支持对多个文件夹下的任意多数据进行批处理使用简单,全自动话,无人工干预功能:提取空洞提取空洞和非空洞默认临时文件夹,结果文件夹默认临时......
  • SpringMVC学习
    SpringMVC是Spring提供的用于简化web开发的框架。 1.5 Servlet能够响应请求的对象。接收请求,返回响应SpringMVC可以认为是Servlet的封装。  1.6SpringMVC开发流程回顾各种配置。Controller,DispatchServlet, 1.7......
  • Field getType 和 getDeclaringClass 两个方法啥区别
    getType()和getDeclaringClass()是Java反射(Reflection)API中Field类的两个方法。这两个方法分别提供了关于字段(Field)的不同信息。以下是它们之间的主要区别:getType()getType()方法返回Field对象表示的字段的Class对象。它表示字段的类型,即字段可以持有的值的类......
  • Go - context
     funcmain(){ctx,cancel:=context.WithTimeout(context.Background(),5*time.Second)defercancel()gof1(ctx)fori:=0;i<10;i++{select{case<-ctx.Done():fmt.Println("timedout"......
  • 在 ESXi 上运行 Cisco Nexus 9000v (NX-OS 10)
    在ESXi上运行CiscoNexus9000v(NX-OS10)在VMwarevSphere中部署CiscoNexus9000v(NX-OS10)请访问原文链接:https://sysin.org/blog/run-nxos-on-esxi/,查看最新版。原创作品,转载请保留出处。作者主页:sysin.orgNexus9000v概述CiscoNexus9000v是虚拟化的Nexus......
  • VMware Cloud Director Availability 4.7 | 灾难恢复和迁移 | DRaaS
    VMwareCloudDirectorAvailability4.7|灾难恢复和迁移|DRaaSOnboarding&DisasterRecoveryServices请访问原文链接:https://sysin.org/blog/vmware-cloud-director-availability-4/,查看最新版。原创作品,转载请保留出处。作者主页:sysin.orgVMwareCloudDirectorAva......
  • CrossOver 24 for Mac:在 macOS 上运行 Windows 应用
    CrossOver24forMac:在macOS上运行Windows应用请访问原文链接:https://sysin.org/blog/crossover/,查看最新版。原创作品,转载请保留出处。作者主页:sysin.orgCrossOver:在macOS、Linux和ChromeOS上运行您的Windows®应用对比所有跨平台方案对比内容CrossOver™......