using MoonExp.cs; using MoonExp.Models; using Npgsql; using System; using System.Collections.Generic; using System.Data.Common; using System.Diagnostics; using System.IO; using System.Linq; using System.Web; namespace MoonExp { public class Tools { /// /// 基础目录 /// public static readonly string BaseDir = AppDomain.CurrentDomain.BaseDirectory; private static PostgreHelper _dbHelper; /// /// DB帮助类 /// public static PostgreHelper DBHelper { get { if (null == _dbHelper) { _dbHelper = new PostgreHelper(); } return _dbHelper; } } /// /// 根据停牌获取用户ID /// public static int SelectUserIdByToken(string token) { string sql = "select create_user from lf.sys_token where token=@token order by create_time desc limit 1;"; DbParameter dp1 = new NpgsqlParameter("@token", token); object obj = DBHelper.GetScalar(sql, dp1); return null == obj ? 0 : int.Parse(obj.ToString()); } /// /// 执行CMD /// /// 命令行 /// 是否为QGIS Py脚本 /// 是否输出错误 /// 执行结果或出错信息 public static string ExecCmd(string cmd, bool isPy = false, bool isOut = false) { List list = new List(); if (isPy) { list.Add("cd \"C:\\Program Files\\QGIS 3.16\\apps\\Python37\""); list.Add("\"C:\\Program Files\\QGIS 3.16\\bin\\qgis_process-qgis-ltr.bat\""); //list.Add("\"C:\\Program Files\\QGIS 3.16\\bin\\python-qgis-ltr.bat\""); //list.Add("exit()"); } list.Add(cmd); string str = ExecCmd(list, isOut); return str; } /// /// 执行CMD /// /// 任务 /// 命令集合 /// 是否输出错误 /// 执行结果或出错信息 public static string ExecCmd(List list, bool isOut = false) { string str; try { Process p = new Process(); p.StartInfo.FileName = "cmd.exe"; p.StartInfo.UseShellExecute = false; p.StartInfo.CreateNoWindow = true; //p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; p.StartInfo.RedirectStandardInput = true; p.StartInfo.RedirectStandardOutput = isOut; p.StartInfo.RedirectStandardError = true; p.Start(); StreamWriter si = p.StandardInput; // 标准输入流 StreamReader so = isOut ? p.StandardOutput : null; // 标准输出流 StreamReader se = p.StandardError; // 标准错误流 LogOut.Info("cmd = " + string.Join(",", list)); si.AutoFlush = true; foreach (string cmd in list) { si.WriteLine(cmd); } si.WriteLine("exit"); string info = null == so ? null : so.ReadToEnd(); str = se.ReadToEnd(); //if (!string.IsNullOrEmpty(info)) LogOut.Debug(info); if (!string.IsNullOrEmpty(str) && !str.Contains("@jit(cache=True, nogil=True)")) LogOut.Error(str); if (p.HasExited == false) p.Kill(); if (null != so) so.Close(); se.Close(); si.Close(); p.Close(); } catch (Exception ex) { LogOut.Error(ex.Message + "\r\n" + ex.StackTrace); str = ex.Message; } return str; } } }