-2

I am trying to save a number of images and I'd like to use the DateTime to have distinct and identifiable Filenames. So I create a String with the correct Path, add the datetime to it and remove the spaces, dots and colons.

        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);

According to the console output the String doesnt change at all. Meaning all the Output Strings from Console.Writeline are identical. I am using c# in visual Studio Express 2010 in case that makes a difference. Can anyone find an Error here?

Thanks in advance!

Andy G
  • 19,232
  • 5
  • 47
  • 69
Andy
  • 337
  • 1
  • 3
  • 14

4 Answers4

15

Strings are immutable, the modified string will be a new string that is returned from the function

e.g.

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

Why strings are immutable

Community
  • 1
  • 1
Matthew Mcveigh
  • 5,695
  • 22
  • 22
2

Why not just use DateTime.ToString() with a format and drop the dividers using that? Would be more efficient than performing several String.Replace() yourself:

string imagePath = "D:\\Patienten\\" + username + "\\" + DateTime.Now.ToString("yyyyMMdd hhmmssfff") + ".png";
Lloyd
  • 29,197
  • 4
  • 84
  • 98
  • works like a charm. Thank you! Is that actually faster then using replace? Considering the method probably uses very similar mechanics... No criticism intended, you just sound as if you knew what you were talking about and I am curious :) – Andy Sep 09 '13 at 14:37
  • I haven't done any tests myself really but I assume it uses `StringBuilder` internally and avoids all the repeated finding, replacing and string operations. – Lloyd Sep 09 '13 at 14:41
1

You should use:

imagePath = imagePath.Replace(" ", ""); You should assign returned value
Ashwani
  • 3,463
  • 1
  • 24
  • 31
1

From the documentation (emphasis mine):

Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.

It is supposed to work like that. Use

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

instead.

Bart Friederichs
  • 33,050
  • 15
  • 95
  • 195