使用C#插值时如何处理变量中的空格? [英] How do you handle spaces in variables when using C# interpolation?

查看:67
本文介绍了使用C#插值时如何处理变量中的空格?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用字符串插值法,如何处理传递到命令中的包含空格的变量?例如,如果您的变量中包含空格(例如UNC路径),那么如何处理呢?

With string interpolation, how do you handle variables piped into a command that contain spaces in them? For example, if you have a variable that has spaces in it (like a UNC path), how do you handle that?

当"filePath"变量(即\ ServerName \ testfile.txt)中不存在空格时,此代码有效:

This code works when no spaces are present in the "filePath" variable (i.e.; \ServerName\testfile.txt):

System.Diagnostics.Process.Start("net.exe", $"use X: \\{filePath} {pwd /USER:{usr}").WaitForExit();

但是,一旦遇到其中有空格的路径,上面的命令将不再起作用,因为它无法找到该路径.通常,我会在包含空格的路径周围加上引号,以解决此问题(在其他语言(如PowerShell)中).您如何使用C#插值做类似的事情.

As soon as you encounter a path that has spaces in it, however, the command above no longer works, because it's unable to find the path. Normally, I would apply quotes around a path containing spaces, to counter this (in other languages like PowerShell). How do you do something similar with C# interpolation.

推荐答案

您将在c#中执行此操作,就像在命令行中一样

You would do this in c# just the way you would in the command line

System.Diagnostics.Process.Start("net.exe", $"use X: \"\\{filePath}\" {pwd /USER:{usr}").WaitForExit();

这篇关于使用C#插值时如何处理变量中的空格?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆