如果文件存在覆盖(c#,winform,批处理文件)
发布时间:2020-12-15 22:52:55 所属栏目:百科 来源:网络整理
导读:我是c#的新手,我对使用WinForm完成一个包含表单接收的参数的批处理文件,执行批处理并创建特定文件表示怀疑. 是)我有的: WinForm – 2个字符串变量(ip和user) 批处理文件 – 使用个性化图标在桌面上创建.rdp文件及其快捷方式(手动启动时批处理工作) 我的问题
我是c#的新手,我对使用WinForm完成一个包含表单接收的参数的批处理文件,执行批处理并创建特定文件表示怀疑.
是)我有的: WinForm – > 2个字符串变量(ip和user) 批处理文件 – >使用个性化图标在桌面上创建.rdp文件及其快捷方式(手动启动时批处理工作) 我的问题是代码第一次工作,但如果我尝试更改变量,进程不会运行,文件不会被新信息覆盖,我有一个错误说我没有访问权限. WinForm代码: private void ok_Click(object sender,EventArgs e) { string ipText,userText,defaultFile,rdpFile; ipText = this.ipOutput.Text; userText = this.userOutput.Text; defaultFile = "C:TerminalServerRDbatch.cmd"; rdpFile = "C:TerminalServerRD Arbeitsplatz.rdp"; Console.WriteLine("IP : " + ipText + "; USER : " + userText); Process p = null; try { p = new Process(); p.StartInfo.CreateNoWindow = true; p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; p.StartInfo.FileName = defaultFile; p.StartInfo.Arguments = String.Format("{0} {1}",ipText,userText); p.StartInfo.UseShellExecute = false; p.StartInfo.RedirectStandardOutput = true; p.Start(); p.WaitForExit(); } catch(Exception ex) { Console.WriteLine("Exception Occurred :{0},{1}",ex.Message,ex.StackTrace.ToString()); } } 批处理文件代码 @echo off REM Change this by remming out desktop or all users desktop as you wish REM Make sure that all entries below have " " around them as present rem set Location="AllUsersDesktop" set Location="C:UsersDefaultDesktop" set DisplayName="" set filename="C:TerminalServerRD Arbeitsplatz.rdp" REM point to an ICO file or an icon within an existing EXE rem set icon="C:TerminalServerrohwerderLogo.ico" set icon="C:TerminalServerrohwerderLogo.ico,0" set WorkingDir="C:TerminalServer" del %filename% 2>NUL (echo screen mode id:i:2 echo use multimon:i:0 echo desktopwidth:i:1920 echo desktopheight:i:1080 echo session bpp:i:32 echo winposstr:s:0,3,800,600 echo compression:i:1 echo keyboardhook:i:2 echo audiocapturemode:i:0 echo videoplaybackmode:i:1 echo connection type:i:7 echo networkautodetect:i:1 echo bandwidthautodetect:i:1 echo displayconnectionbar:i:1 echo disable wallpaper:i:0 echo allow font smoothing:i:0 echo allow desktop composition:i:0 echo disable full window drag:i:1 echo disable menu anims:i:1 echo disable themes:i:0 echo disable cursor setting:i:0 echo bitmapcachepersistenable:i:1 echo full address:s:%1 echo audiomode:i:0 echo redirectprinters:i:1 echo redirectcomports:i:0 echo redirectsmartcards:i:1 echo redirectclipboard:i:1 echo redirectposdevices:i:0 echo drivestoredirect:s: echo username:s:%2 echo autoreconnection enabled:i:1 echo authentication level:i:2 echo prompt for credentials:i:0 echo negotiate security layer:i:1 echo remoteapplicationmode:i:0 echo alternate shell:s: echo shell working directory:s: echo gatewayhostname:s: echo gatewayusagemethod:i:4 echo gatewaycredentialssource:i:4 echo gatewayprofileusagemethod:i:0 echo promptcredentialonce:i:0 echo gatewaybrokeringtype:i:0 echo use redirection server name:i:0 echo rdgiskdcproxy:i:0 echo kdcproxyname:s: ) > %filename% attrib %filename% +r echo Y|cacls %filename% /E /P %username%:r REM Make temporary VBS file to create shortcut REM Then execute and delete it set SCRIPT="%TEMP%%RANDOM%-%RANDOM%-%RANDOM%-%RANDOM%.vbs" echo Set oWS = WScript.CreateObject("WScript.Shell") >> %SCRIPT% echo sLinkFile = "%USERPROFILE%DesktopRD Arbeitsplatz.lnk" >> %SCRIPT% echo Set oLink = oWS.CreateShortcut(sLinkFile) >> %SCRIPT% echo oLink.TargetPath = "C:TerminalServerRD Arbeitsplatz.rdp" >> %SCRIPT% echo oLink.IconLocation = "C:TerminalServerrohwerderLogo.ico" >> %SCRIPT% echo oLink.Save >> %SCRIPT% cscript /nologo %SCRIPT% rem del %SCRIPT% 2>NUL 如果文件不存在,如果存在覆盖它,我正在考虑启动进程代码,但我不知道如何从这里开始. 解决方法
我建议尝试仅在C#中完成您的任务,这里有一些代码和我的评论,以便让您前进.通过在方法调用周围添加try / catch块,让我们知道它导致的异常.
** Required usings ** using System.IO; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Security.AccessControl; // Usage of the method // (CommonDesktopDirectory = All Users Desktop or DesktopDirectory = Current user desktop) CreateRdpFile(Environment.SpecialFolder.CommonDesktopDirectory,@"C:TerminalServerrohwerderLogo.ico","127.0.0.1",Environment.UserName ); public void CreateRdpFile(Environment.SpecialFolder locationOfShortcut,string iconPath,string ip,string userName) { // The fileName of the rdp file to create var rdpFileName = @"C:TerminalServerRD Arbeitsplatz.rdp"; // Your filecontents,note that we're concatenation the ip and userName from the methods arguments var rdpFileContent = @"screen mode id:i:2 use multimon:i:0 desktopwidth:i:1920 desktopheight:i:1080 session bpp:i:32 winposstr:s:0,600 compression:i:1 keyboardhook:i:2 audiocapturemode:i:0 videoplaybackmode:i:1 connection type:i:7 networkautodetect:i:1 bandwidthautodetect:i:1 displayconnectionbar:i:1 disable wallpaper:i:0 allow font smoothing:i:0 allow desktop composition:i:0 disable full window drag:i:1 disable menu anims:i:1 disable themes:i:0 disable cursor setting:i:0 bitmapcachepersistenable:i:1 full address:s:" + ip + @" audiomode:i:0 redirectprinters:i:1 redirectcomports:i:0 redirectsmartcards:i:1 redirectclipboard:i:1 redirectposdevices:i:0 drivestoredirect:s: username:s:"+ userName +@" autoreconnection enabled:i:1 authentication level:i:2 prompt for credentials:i:0 negotiate security layer:i:1 remoteapplicationmode:i:0 alternate shell:s: shell working directory:s: gatewayhostname:s: gatewayusagemethod:i:4 gatewaycredentialssource:i:4 gatewayprofileusagemethod:i:0 promptcredentialonce:i:0 gatewaybrokeringtype:i:0 use redirection server name:i:0 rdgiskdcproxy:i:0 kdcproxyname:s:"; // Open a filestream,load that into a streamWriter using (var fileStream = File.Open(rdpFileName,FileMode.Create)) using(var streamWriter = new StreamWriter(fileStream)) { // Write the contents of the string created above streamWriter.Write(rdpFileContent); } // fileStream and streamWriter automatically closed because of using block // Get a FileSecurity object that represents the // current security settings. FileSecurity fSecurity = File.GetAccessControl(rdpFileName); // Add the FileSystemAccessRule to the security settings. (Allow read for user from argument) fSecurity.AddAccessRule(new FileSystemAccessRule(userName,FileSystemRights.Read,AccessControlType.Allow)); // Build the shortcut path var shortcutPath = Path.Combine(Environment.GetFolderPath(locationOfShortcut),"RD Arbeitsplatz.lnk"); IShellLink link = (IShellLink)new ShellLink(); // Setup shortcut information link.SetDescription("My Description"); link.SetPath(rdpFileName); link.SetIconLocation(iconPath); // Save it var file = (IPersistFile)link; file.Save(shortcutPath,false); } #region Imported code to prevent additional assembly references [ComImport] [Guid("00021401-0000-0000-C000-000000000046")] internal class ShellLink { } [ComImport] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] [Guid("000214F9-0000-0000-C000-000000000046")] internal interface IShellLink { void GetPath([Out,MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszFile,int cchMaxPath,out IntPtr pfd,int fFlags); void GetIDList(out IntPtr ppidl); void SetIDList(IntPtr pidl); void GetDescription([Out,MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszName,int cchMaxName); void SetDescription([MarshalAs(UnmanagedType.LPWStr)] string pszName); void GetWorkingDirectory([Out,MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszDir,int cchMaxPath); void SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string pszDir); void GetArguments([Out,MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszArgs,int cchMaxPath); void SetArguments([MarshalAs(UnmanagedType.LPWStr)] string pszArgs); void GetHotkey(out short pwHotkey); void SetHotkey(short wHotkey); void GetShowCmd(out int piShowCmd); void SetShowCmd(int iShowCmd); void GetIconLocation([Out,MarshalAs(UnmanagedType.LPWStr)] StringBuilder pszIconPath,int cchIconPath,out int piIcon); void SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string pszIconPath,int iIcon); void SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string pszPathRel,int dwReserved); void Resolve(IntPtr hwnd,int fFlags); void SetPath([MarshalAs(UnmanagedType.LPWStr)] string pszFile); } #endregion (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |