Search code examples
c#if-statementstartswith

If statement based on StartsWith not finding "\\" in C#


I have a string called fileNameArrayEdited which contains "\\windows".The below if statement is not running.

Thinking the problem is else where as people have given me code that should work will be back once I found the problem... thanks!

if (fileNameArrayEdited.StartsWith("\\"))
{
    specifiedDirCount = specifiedDirCount + 1;
}

                // Put all file names in root directory into array.
            string[] fileNameArray = Directory.GetFiles(@specifiedDir);
            int specifiedDirCount = specifiedDir.Count();
            string fileNameArrayEdited = specifiedDir.Remove(0, specifiedDirCount);
            Console.WriteLine(specifiedDir.Remove(0, specifiedDirCount));
            if (fileNameArrayEdited.StartsWith(@"\\"))
            {
                specifiedDirCount = specifiedDirCount + 1;
                Console.ReadLine();

Solution

  • Use '@' at the beginning of your string if you are searching for exactly two slash

    if (fileNameArrayEdited.StartsWith(@"\\"))
    {
      specifiedDirCount = specifiedDirCount + 1;
    }
    

    They are called verbatim strings and they are ignoring escape characters.For better explanation you can take a look at here: http://msdn.microsoft.com/en-us/library/362314fe.aspx

    But I suspect in here your one slash is escape character

    "\\windows"
    

    So you must search for one slash like this:

    if (fileNameArrayEdited.StartsWith(@"\"))
    {
      specifiedDirCount = specifiedDirCount + 1;
    }