0

I need to use a string for path for a file but sometimes there are forbidden characters in this string and I must replace them. For example, my string _title is rumbaton jonathan \"racko\" contreras.

Well I should replace the chars \ and ".

I tried this but it doesn't work:

_title.Replace(@"/", "");
_title.Replace(@"\", "");
_title.Replace(@"*", "");
_title.Replace(@"?", "");
_title.Replace(@"<", "");
_title.Replace(@">", "");
_title.Replace(@"|", "");
rae1
  • 6,066
  • 4
  • 27
  • 48
Veriditas
  • 113
  • 2
  • 11

6 Answers6

4

Since strings are immutable, the Replace method returns a new string, it doesn't modify the instance you are calling it on. So try this:

_title = _title
    .Replace(@"/", "")
    .Replace(@"""", "")
    .Replace(@"*", "")
    .Replace(@"?", "")
    .Replace(@"<", "")
    .Replace(@">", "")
    .Replace(@"|", "");

Also if you want to replace " make sure you have properly escaped it.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
2

Try regex

string illegal = "\"M\"\\a/ry/ h**ad:>> a\\/:*?\"| li*tt|le|| la\"mb.?";
string regexSearch = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
Regex r = new Regex(string.Format("[{0}]", Regex.Escape(regexSearch)));
illegal = r.Replace(illegal, "");

Before: "M"\a/ry/ h**ad:>> a/:?"| litt|le|| la"mb.? After: Mary had a little lamb.

Also another answer from same post is much cleaner

private static string CleanFileName(string fileName)
{
    return Path.GetInvalidFileNameChars().Aggregate(fileName, (current, c) => current.Replace(c.ToString(), string.Empty));
}

from How to remove illegal characters from path and filenames?

Community
  • 1
  • 1
Mayank
  • 8,777
  • 4
  • 35
  • 60
  • Do look at the 2nd answer, much cleaner. – H H Aug 21 '13 at 16:00
  • @HenkHolterman there are no first, second or any order of answers, they are sorted by the number of votes and that is subject to change – user1306322 Aug 21 '13 at 16:01
  • @user1306322 There is if you compare the times of each answer and look for the oldest > youngest – DGibbs Aug 21 '13 at 16:11
  • @DGibbs very soon it will be difficult to do so, since the minutes won't be visible, and I doubt anybody would go through the trouble of comparing the posting dates visually. Unless they *really* want to find out what happened here. – user1306322 Aug 21 '13 at 16:51
  • @user1306322 At the time he posted his comment, it was quite easy to determine the 2nd post by time due to minutes being visible. Now, not so much. As they age I believe the minutes are shown again along with hrs/day/month/year etc... – DGibbs Aug 21 '13 at 17:01
  • 1
    @DGibbs oh, you're right! This oldest question has exact dates near all posted answers: http://stackoverflow.com/q/4/1306322 – user1306322 Aug 21 '13 at 17:08
1

Or you could try this (probably terribly inefficient) method:

string inputString = @"File ~!@#$%^&*()_+|`1234567890-=\[];',./{}:""<>? name";
var badchars = Path.GetInvalidFileNameChars();
foreach (var c in badchars)
    inputString = inputString.Replace(c.ToString(), "");

The result will be:

File ~!@#$%^&()_+`1234567890-=[];',.{} name

But feel free to add more chars to the badchars before running the foreach loop on them.

user1306322
  • 8,561
  • 18
  • 61
  • 122
0

See http://msdn.microsoft.com/cs-cz/library/fk49wtc1.aspx:

Returns a string that is equivalent to the current string except that all instances of oldValue are replaced with newValue.

Martin Podval
  • 1,097
  • 1
  • 7
  • 16
0

I have written a method to do the exact operation that you want and with much cleaner code.

The method

public static string Delete(this string target, string samples) {
    if (string.IsNullOrEmpty(target) || string.IsNullOrEmpty(samples))
        return target;
    var tar = target.ToCharArray();
    const char deletechar = '♣'; //a char that most likely never to be used in the input
    for (var i = 0; i < tar.Length; i++) {
        for (var j = 0; j < samples.Length; j++) {
            if (tar[i] == samples[j]) {
                tar[i] = deletechar;
                break;
            }
        }
    }
    return tar.ConvertToString().Replace(deletechar.ToString(CultureInfo.InvariantCulture), string.Empty);
}

Sample

var input = "rumbaton jonathan \"racko\" contreras";
var cleaned = input.Delete("\"\\/*?><|");

Will result in:

rumbaton jonathan racko contreras

Community
  • 1
  • 1
NucS
  • 619
  • 8
  • 21
0

Ok ! I've solved my issue thanks to all your indications. This is my correction :

string newFileName = _artist + " - " + _title;
char[] invalidFileChars = Path.GetInvalidFileNameChars();
char[] invalidPathChars = Path.GetInvalidPathChars();
foreach (char invalidChar in invalidFileChars)
{
        newFileName = newFileName.Replace(invalidChar.ToString(), string.Empty);
}
foreach (char invalidChar in invalidPathChars)
{
        newFilePath = newFilePath.Replace(invalidChar.ToString(), string.Empty);
}

Thank you so musch everybody :)

Veriditas
  • 113
  • 2
  • 11