You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Android MAUI应用实现Windows共享传文件并远程执行CMD命令

Android MAUI实现远程向Windows共享目录传输CMD命令脚本

问题背景

需求:从安卓手机远程运行Windows电脑的CMD命令
当前方案:Windows端通过WPF应用监听D:\Shared目录下带.dev后缀的文件;手机端需手动编写.bat文件,借助第三方APP传输至该共享目录,操作流程繁琐。
目标:开发Android MAUI应用,自动完成.bat文件创建及Windows共享目录传输,适配现有WPF监听逻辑。

附现有WPF监听核心代码:

using Microsoft.Win32;
using System.Diagnostics;

namespace Dev
{
    public partial class Dev : ApplicationContext
    {
        class Var
        {
            public static string temp = Path.GetTempPath();
        }
        public Dev()
        {
            RegistryKey key = Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\RunOnce", true);
            key.SetValue("Remote Dev", Application.ExecutablePath);

            FileSystemWatcher watcher = new()
            {
                Path = "D:\\Shared",
                NotifyFilter = NotifyFilters.LastAccess | NotifyFilters.LastWrite
               | NotifyFilters.FileName | NotifyFilters.DirectoryName,
                Filter = "*.dev.*"
            };

            watcher.Created += new FileSystemEventHandler(Create);
            watcher.EnableRaisingEvents = true;
        }

        static void Create(object source, FileSystemEventArgs e)
        {
            string tempPath = Var.temp + Path.GetFileName(e.FullPath);

            if (File.Exists(tempPath)) File.Delete(tempPath);
            File.Move(e.FullPath, tempPath);
            Thread.Sleep(1000);
            Process.Start("explorer", tempPath);
        }
    }
}

解决方案实现

一、MAUI应用核心功能设计

MAUI应用需完成两个核心动作:

  • 接收用户输入的CMD命令,自动生成符合.dev.*命名规则的脚本文件
  • 将生成的文件上传至Windows共享目录D:\Shared

二、具体开发步骤

1. 创建MAUI Android项目

新建MAUI项目后,在项目属性中仅保留Android平台支持,减少不必要的资源开销。

2. 实现CMD命令输入与脚本生成

在MainPage.xaml中添加输入框与操作按钮:

<ContentPage xmlns="http://schemas.microsoft.com/dotnet/2021/maui"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="RemoteCmdSender.MainPage">

    <VerticalStackLayout Padding="20">
        <Entry x:Name="CmdInput" Placeholder="输入要执行的CMD命令" 
               HeightRequest="100" VerticalOptions="FillAndExpand" />
        <Button x:Name="SendBtn" Text="发送命令" Clicked="SendBtn_Clicked" 
                Margin="0,10,0,0" />
        <Label x:Name="StatusLabel" Margin="0,10,0,0" />
    </VerticalStackLayout>
</ContentPage>

后台代码实现脚本生成逻辑:

private async void SendBtn_Clicked(object sender, EventArgs e)
{
    if (string.IsNullOrWhiteSpace(CmdInput.Text))
    {
        StatusLabel.Text = "请输入CMD命令";
        return;
    }

    // 生成符合WPF监听规则的文件名:随机ID.dev.bat
    string fileName = $"{Guid.NewGuid()}.dev.bat";
    string fileContent = CmdInput.Text;

    // 保存到应用缓存目录(无需额外存储权限)
    string filePath = Path.Combine(FileSystem.Current.CacheDirectory, fileName);
    await File.WriteAllTextAsync(filePath, fileContent);

    // 执行上传操作
    bool uploadSuccess = await UploadToSharedFolder(filePath, fileName);
    StatusLabel.Text = uploadSuccess ? "命令发送成功" : "命令发送失败";
}

3. 实现SMB共享目录上传

通过NuGet安装SMBLibrary包,实现跨平台SMB协议文件传输:

using SMBLibrary;
using SMBLibrary.Client;

private async Task<bool> UploadToSharedFolder(string localFilePath, string fileName)
{
    try
    {
        // 配置Windows共享参数
        string serverIp = "你的Windows电脑局域网IP";
        string shareName = "Shared"; // D:\Shared对应的共享名称
        string winUsername = "Windows登录账号";
        string winPassword = "Windows登录密码";

        using (SMBClient client = new SMBClient())
        {
            // 连接SMB服务器
            client.Connect(serverIp, SMBTransportType.DirectTCPTransport);
            NTStatus loginStatus = client.Login(shareName, winUsername, winPassword);
            if (loginStatus != NTStatus.STATUS_SUCCESS) return false;

            // 连接共享目录
            ISMBFileStore fileStore = client.TreeConnect(shareName, out NTStatus connectStatus);
            if (connectStatus != NTStatus.STATUS_SUCCESS) return false;

            // 读取本地文件内容
            byte[] fileBytes = await File.ReadAllBytesAsync(localFilePath);

            // 写入共享目录
            using (SMBFile file = fileStore.CreateFile(fileName, FileAccessMask.GENERIC_WRITE, 
                   FileAttributes.Normal, ShareAccess.Read, CreateDisposition.CreateNew, CreateOptions.None))
            {
                file.WriteFile(0, fileBytes, out int bytesWritten);
                return bytesWritten == fileBytes.Length;
            }
        }
    }
    catch (Exception)
    {
        return false;
    }
}

4. 优化WPF监听逻辑(可选)

原WPF代码仅打开脚本文件,若需直接执行CMD命令,修改Create方法:

static void Create(object source, FileSystemEventArgs e)
{
    string tempPath = Var.temp + Path.GetFileName(e.FullPath);

    if (File.Exists(tempPath)) File.Delete(tempPath);
    File.Move(e.FullPath, tempPath);
    Thread.Sleep(1000);
    
    // 替换原打开操作,改为执行bat文件
    Process.Start(new ProcessStartInfo
    {
        FileName = "cmd.exe",
        Arguments = $"/c \"{tempPath}\"",
        WindowStyle = ProcessWindowStyle.Hidden // 可选:隐藏CMD窗口
    });
}

三、关键注意事项

  • 确保Windows电脑的D:\Shared已开启共享权限,且安卓设备与Windows处于同一局域网
  • Windows防火墙需允许SMB协议(端口445)的入站连接
  • MAUI Android应用需在Platforms/Android/AndroidManifest.xml中添加权限:
    <uses-permission android:name="android.permission.INTERNET" />
    

内容的提问来源于stack exchange,提问作者User not found

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 14:30:53