Marcus
Marcus

Reputation: 449

C# Compiler error with Substring

Why I'm getting:

Index and length must refer to a location within the string.
Parameter name: length

when I compile this code: http://pastebin.com/CW4EcCM8

some part of it:

    public string findFileEnding(string file)
    {
        int index1 = file.IndexOf('.');
        file = file.Substring(index1, file.Length);
        return file;
    }

Thanks;)

Upvotes: 0

Views: 246

Answers (4)

Valentin Kuzub
Valentin Kuzub

Reputation: 12093

I am thinking there is a chance Path.GetExtension could be something OP might want instead.

notice that it returns extension with . like .exe

http://msdn.microsoft.com/en-us/library/system.io.path.getextension.aspx

Upvotes: 4

John
John

Reputation: 6553

You would want to do something like this:

public string FindFileEnding(string file)
{
    if (string.IsNullOrEmpty(file))
    {
        // Either throw exception or handle the file here
        throw new ArgumentNullException();
    }
    try
    {
        return file.Substring(file.LastIndexOf('.'));
    }
    catch (Exception ex)
    {
        // Handle the exception here if you want, or throw it to the calling method
        throw ex;
    }
}

Upvotes: 0

Jeffrey Sax
Jeffrey Sax

Reputation: 10323

The second argument to Substring, if present, is the desired length of the substring. So you're asking for a string the same length as file but starting at a position possibly different from 0. This would make the end of your substring to be past the end of file.

Assuming you want to get all of file starting at position index1, you can just leave out the second argument altogether:

file = file.Substring(index1); 

To make this robust, you'll want to put in a few more checks:

  1. file may be null.
  2. The return value of IndexOf may be -1. This would happen if file does not contain a dot.

Upvotes: 2

jason
jason

Reputation: 241789

That's not a compiler error, that's a runtime error.

Note the documentation for String.Substring(int, int):

Retrieves a substring from this instance. The substring starts at a specified character position [startIndex] and has a specified length [length].

So the substring will have the specified length. Therefore, there must be enough characters starting at startIndex to return a substring of the specified length. Therefore, the following inequalities must be satisfied for String.Substring to succeed on an instance s of string:

startIndex >= 0
length >= 0
length > 0 implies startIndex + length <= s.Length

Note that if you just want a substring from index to the end of the string, you can say

s.Substring(index);

Here, the only constraint is

startIndex>= 0
startIndex < s.Length

Upvotes: 0

Related Questions