Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/261.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 字符串。替换不修改我的字符串_C#_String_Replace - Fatal编程技术网

C# 字符串。替换不修改我的字符串

C# 字符串。替换不修改我的字符串,c#,string,replace,C#,String,Replace,我正在尝试保存一些图像,我想使用DateTime来拥有不同的和可识别的文件名。 因此,我创建了一个具有正确路径的字符串,将datetime添加到其中,并删除空格、点和冒号 String imagePath = "D:\\Patienten\\" + username; imagePath += "\\"+DateTime.Now.ToString(); Console.WriteLine("WithFilename: " + imagePath);

我正在尝试保存一些图像,我想使用DateTime来拥有不同的和可识别的文件名。 因此,我创建了一个具有正确路径的字符串,将datetime添加到其中,并删除空格、点和冒号

        String imagePath = "D:\\Patienten\\" + username;
        imagePath += "\\"+DateTime.Now.ToString();
        Console.WriteLine("WithFilename: " + imagePath);
        imagePath.Replace(" ", "");
        Console.WriteLine("Without \" \" : " + imagePath);
        imagePath.Replace(".", "");
        Console.WriteLine("Without \".\": " + imagePath);
        imagePath.Replace(":", "");
        Console.WriteLine("Output format: " + imagePath);
        imagePath += ".png";
        image.Save(imagePath);
根据控制台输出,字符串根本没有改变。 这意味着Console.Writeline中的所有输出字符串都是相同的。 我正在VisualStudioExpress 2010中使用c#,以防这会产生影响。 有人能在这里找到错误吗


提前谢谢

字符串是不可变的,修改后的字符串将是从函数返回的新字符串

e、 g

您应该使用:

imagePath = imagePath.Replace(" ", ""); You should assign returned value
从(我的)重点:

返回一个新字符串,在该字符串中,当前实例中指定字符串的所有匹配项都替换为另一个指定字符串

它应该是这样工作的。使用

imagePath = imagePath.Replace(" ", "");

相反。

为什么不使用带有格式的
DateTime.ToString()
并使用该格式删除分隔符呢?比自己执行几个
String.Replace()
更有效:

string imagePath = "D:\\Patienten\\" + username + "\\" + DateTime.Now.ToString("yyyyMMdd hhmmssfff") + ".png";

imagePath=imagePath.Replace(“,”)字符串是不可变的。从文档中可以看出:“此方法不修改当前实例的值。相反,它返回一个新字符串,其中所有出现的oldValue都被newValue替换。”这个问题经常出现。请下次搜索。您可以将此添加为有用的链接:像符咒一样工作。非常感谢。这实际上比使用replace更快吗?考虑到该方法可能使用非常相似的力学。。。没有批评的意思,你只是听起来好像知道你在说什么,我很好奇:)我自己没有做任何测试,但我认为它在内部使用
StringBuilder
,避免了所有重复的查找、替换和字符串操作。
string imagePath = "D:\\Patienten\\" + username + "\\" + DateTime.Now.ToString("yyyyMMdd hhmmssfff") + ".png";