使用C# 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";
        }
    }
}

posted @ 2024-02-23 12:31  迷路的哨兵甲  阅读(303)  评论(0编辑  收藏  举报