locked
error StartIndex cannot be less than zero. RRS feed

  • Question

  • i have a page that upload files to folder depend on user primession

    everything was ok but today i notice that this page give this error

    StartIndex cannot be less than zero.
    Parameter name: startIndex

    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.ArgumentOutOfRangeException: StartIndex cannot be less than zero.
    Parameter name: startIndex

    Source Error:

    Line 250:          '-- replace spaces with "_" in the filename to make it URL encoding compatable
    Line 251:          Dim lastslash As Integer = pf.FileName.LastIndexOf("\")
    Line 252:          Dim strnonspaces As String = strFilename.Substring(lastslash).Replace(" ", " ")
    Line 253:          strnonspaces = strnonspaces.Replace("&", "and")
    Line 254:          strFilename = strFilename.Substring(0, lastslash) + strnonspaces

     

    and i don't why or how to fix it


    Thanks for any help :) my blog is: http://www.waelk.com
    Tuesday, June 29, 2010 2:34 PM

Answers

  • if you debug the code, you will find out the lastslash is return -1, which means pf does not contain back slash. And you are passing negative number to substring method

    Dim lastslash As Integer = pf.FileName.LastIndexOf("\")

    try to debug andd you can see the value of lastslash

    kaymaf


    CODE CONVERTER SITE

    http://www.carlosag.net/Tools/CodeTranslator/.

    http://www.developerfusion.com/tools/convert/csharp-to-vb/.

    • Marked as answer by Alex Liang Tuesday, July 6, 2010 12:14 PM
    Tuesday, June 29, 2010 2:50 PM
  • I imagine that LastIndexOf did not, in fact find a slash. (In which case, it will return -1...an illegal index.) You should always check the return of functions, escpecially those that attempt to find things in strings. I just use Replace("\", "/"). FYI, however...there is a function that will fix up your query string...assuming that is what you are doing...Control.ResolveURL

     

    • Marked as answer by Alex Liang Tuesday, July 6, 2010 12:15 PM
    Tuesday, June 29, 2010 2:57 PM
  • on top of what everyone else said, in order to prevent the IndexOutOfRange, you can check if the String contains a \ before calling the LastIndexOf

    so insert an If Then block

    If pf.FileName.Contains("\") Then
    Dim lastslash As Integer = ...
    • Marked as answer by Alex Liang Tuesday, July 6, 2010 12:14 PM
    Tuesday, June 29, 2010 3:33 PM
  • it appears your code is looking for a file in a directory or root folder. in this case the file was not passed (no slash was found). you probably need to handle this to make sure other codes that depend on this file do not brake. 

    first, you may need to replace line 252 with:

    Dim strnonspaces As String
    if lastslash >=0 then strnonspaces = strFilename.Substring(lastslash).Replace(" ", " ") 

    If the file is required for your application, then consider adding an else code to handle the exception

    hope this helps.


    Wisdom is of God. James 1:5
    • Marked as answer by Alex Liang Tuesday, July 6, 2010 12:15 PM
    Wednesday, June 30, 2010 4:01 AM
  • Hi,

    the problem you have now is that your strnonspaces is nothing. But maybe you need to think about the whole problem first, why the first exception has occured: There hasen`t been a \ in the strfilename variable. If it is a valid filename, there should have been one. Maybe better to check first the value of strfilname by putting a breakpoint at Dim lastslash As Integer = pf.FileName.LastIndexOf("\")


    Hannes

    If you have got questions about this, just ask.
    Mark the thread as answered if the answer helps you. This helps others who have the same problem !
    C# to VB.NET: http://www.developerfusion.com/tools/convert/csharp-to-vb/
    • Marked as answer by Alex Liang Tuesday, July 6, 2010 12:14 PM
    Wednesday, June 30, 2010 8:30 AM
  • Replace the indexof style code and use the path class

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

    It is easier and more sufficient.

     

     


    Success
    Cor
    • Marked as answer by Alex Liang Tuesday, July 6, 2010 12:14 PM
    Wednesday, June 30, 2010 9:13 AM
  • why not use FileInfo Class,  a member of System.IO to get filename, path directory and other file operations instead of LastIndexOf?

    it will save you time and bugs.

    Try replacing your code with this: 

    Private Sub SaveUploadedFile()
        If Request.Files.Count > 0 Then
          Dim pf As HttpPostedFile = Request.Files.Item(0)
          If pf.ContentLength > 0 Then
            Dim srcFile As FileInfo = New FileInfo(pf.FileName)
            Dim strFilename As String = srcFile.Name
            '-- replace spaces with "_" in the filename to make it URL encoding compatable, & with and.
            strFilename = strFilename.Replace(" ", "_").Replace("&", "and")
    
            Dim strTargetFile As String = Path.Combine(srcFile.DirectoryName, strFilename)
            '-- make sure we clear out any existing file before uploading
            If File.Exists(strTargetFile) Then
              DeleteFileOrFolder(strFilename)
            End If
            Try
              pf.SaveAs(strTargetFile)
            Catch ex As Exception
              _FileOperationException = ex
            End Try
          End If
        End If
      End Sub

    Remember to add Imports System.IO at the very  top of your code file.


    Wisdom is of God. James 1:5
    • Marked as answer by Alex Liang Tuesday, July 6, 2010 12:14 PM
    Wednesday, June 30, 2010 7:42 PM

All replies

  • Hi,

    using the substring() you need to pass a value >0. I guess that by calling the LastIndexOf() method here

    Dim lastslash as Integer ... just a line above

    the the pf.FileName doesn`t contain a "\" so it results in lastslash=-1

     


    Hannes

    If you have got questions about this, just ask.
    Mark the thread as answered if the answer helps you. This helps others who have the same problem !
    C# to VB.NET: http://www.developerfusion.com/tools/convert/csharp-to-vb/
    Tuesday, June 29, 2010 2:49 PM
  • if you debug the code, you will find out the lastslash is return -1, which means pf does not contain back slash. And you are passing negative number to substring method

    Dim lastslash As Integer = pf.FileName.LastIndexOf("\")

    try to debug andd you can see the value of lastslash

    kaymaf


    CODE CONVERTER SITE

    http://www.carlosag.net/Tools/CodeTranslator/.

    http://www.developerfusion.com/tools/convert/csharp-to-vb/.

    • Marked as answer by Alex Liang Tuesday, July 6, 2010 12:14 PM
    Tuesday, June 29, 2010 2:50 PM
  • I imagine that LastIndexOf did not, in fact find a slash. (In which case, it will return -1...an illegal index.) You should always check the return of functions, escpecially those that attempt to find things in strings. I just use Replace("\", "/"). FYI, however...there is a function that will fix up your query string...assuming that is what you are doing...Control.ResolveURL

     

    • Marked as answer by Alex Liang Tuesday, July 6, 2010 12:15 PM
    Tuesday, June 29, 2010 2:57 PM
  • on top of what everyone else said, in order to prevent the IndexOutOfRange, you can check if the String contains a \ before calling the LastIndexOf

    so insert an If Then block

    If pf.FileName.Contains("\") Then
    Dim lastslash As Integer = ...
    • Marked as answer by Alex Liang Tuesday, July 6, 2010 12:14 PM
    Tuesday, June 29, 2010 3:33 PM
  • it appears your code is looking for a file in a directory or root folder. in this case the file was not passed (no slash was found). you probably need to handle this to make sure other codes that depend on this file do not brake. 

    first, you may need to replace line 252 with:

    Dim strnonspaces As String
    if lastslash >=0 then strnonspaces = strFilename.Substring(lastslash).Replace(" ", " ") 

    If the file is required for your application, then consider adding an else code to handle the exception

    hope this helps.


    Wisdom is of God. James 1:5
    • Marked as answer by Alex Liang Tuesday, July 6, 2010 12:15 PM
    Wednesday, June 30, 2010 4:01 AM
  • first : it is not my application i just try to fix this problem.

    the wird is that with IE6 it is upload the file with no error but this error display with IE7 and IE8 as i know as developer it must work with all version of IE, aim totaly lost in this problem

    this funaction code is:

     ''' <summary>
        ''' Saves the first HttpPostedFile (if there is one) to the current folder
        ''' </summary>
        Private Sub SaveUploadedFile()
          If Request.Files.Count > 0 Then
            Dim pf As HttpPostedFile = Request.Files.Item(0)
            If pf.ContentLength > 0 Then
              Dim strFilename As String = pf.FileName
              '-- replace spaces with "_" in the filename to make it URL encoding compatable
              Dim lastslash As Integer = pf.FileName.LastIndexOf("\")
              Dim strnonspaces As String = strFilename.Substring(lastslash).Replace(" ", "_")
              strnonspaces = strnonspaces.Replace("&", "and")
              strFilename = strFilename.Substring(0, lastslash) + strnonspaces
    
              Dim strTargetFile As String = GetLocalPath(Path.GetFileName(strFilename))
              '-- make sure we clear out any existing file before uploading
              If File.Exists(strTargetFile) Then
                DeleteFileOrFolder(strFilename)
              End If
              Try
                pf.SaveAs(strTargetFile)
              Catch ex As Exception
                _FileOperationException = ex
              End Try
            End If
          End If
        End Sub
    so please any more help in this it will usefual
    Thanks for any help :) my blog is: http://www.waelk.com
    Wednesday, June 30, 2010 7:27 AM
  • owolabi: i change with your line of code and it give me this error

    Object reference not set to an instance of an object.

    Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

    Exception Details: System.NullReferenceException: Object reference not set to an instance of an object.

    Source Error:

    Line 254:          If lastslash >= 0 Then strnonspaces = strFilename.Substring(lastslash).Replace(" ", " ")
    Line 255:          'Dim strnonspaces As String = strFilename.Substring(lastslash).Replace(" ", " ")
    Line 256:          strnonspaces = strnonspaces.Replace("&", "and")
    Line 257:          strFilename = strFilename.Substring(0, lastslash) + strnonspaces
    Line 258:

    Source File: e:\inetpub\wwwroot\WFM\ISfilemanager.aspx.vb    Line: 256

    Stack Trace:

    [NullReferenceException: Object reference not set to an instance of an object.]
      WebFileManager._default.SaveUploadedFile() in e:\inetpub\wwwroot\WFM\ISfilemanager.aspx.vb:256
      WebFileManager._default.HandleAction() in e:\inetpub\wwwroot\WFM\ISfilemanager.aspx.vb:165
      ASP.wfm_isfilemanager_aspx.__Render__control1(HtmlTextWriter __w, Control parameterContainer) in e:\inetpub\wwwroot\WFM\ISfilemanager.aspx:482
      System.Web.UI.Control.RenderChildrenInternal(HtmlTextWriter writer, ICollection children) +256
      System.Web.UI.Control.RenderChildren(HtmlTextWriter writer) +19
      System.Web.UI.Page.Render(HtmlTextWriter writer) +29
      System.Web.UI.Control.RenderControlInternal(HtmlTextWriter writer, ControlAdapter adapter) +27
      System.Web.UI.Control.RenderControl(HtmlTextWriter writer, ControlAdapter adapter) +99
      System.Web.UI.Control.RenderControl(HtmlTextWriter writer) +25
      System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint) +1266
    


    bs: i try to upload in the server using same url it upload but in my pc give me this error

    the funcation after change with your line of code be this:

    ''' <summary>
        ''' Saves the first HttpPostedFile (if there is one) to the current folder
        ''' </summary>
        Private Sub SaveUploadedFile()
          If Request.Files.Count > 0 Then
            Dim pf As HttpPostedFile = Request.Files.Item(0)
            If pf.ContentLength > 0 Then
              Dim strFilename As String = pf.FileName
              '-- replace spaces with "_" in the filename to make it URL encoding compatable
              Dim lastslash As Integer = pf.FileName.LastIndexOf("\")
    
              Dim strnonspaces As String
              If lastslash >= 0 Then strnonspaces = strFilename.Substring(lastslash).Replace(" ", " ")
              'Dim strnonspaces As String = strFilename.Substring(lastslash).Replace(" ", " ")
              strnonspaces = strnonspaces.Replace("&", "and")
              strFilename = strFilename.Substring(0, lastslash) + strnonspaces
    
              Dim strTargetFile As String = GetLocalPath(Path.GetFileName(strFilename))
              '-- make sure we clear out any existing file before uploading
              If File.Exists(strTargetFile) Then
                DeleteFileOrFolder(strFilename)
              End If
              Try
                pf.SaveAs(strTargetFile)
              Catch ex As Exception
                _FileOperationException = ex
              End Try
            End If
          End If
        End Sub

    Thanks for any help :) my blog is: http://www.waelk.com
    Wednesday, June 30, 2010 8:21 AM
  • Hi,

    the problem you have now is that your strnonspaces is nothing. But maybe you need to think about the whole problem first, why the first exception has occured: There hasen`t been a \ in the strfilename variable. If it is a valid filename, there should have been one. Maybe better to check first the value of strfilname by putting a breakpoint at Dim lastslash As Integer = pf.FileName.LastIndexOf("\")


    Hannes

    If you have got questions about this, just ask.
    Mark the thread as answered if the answer helps you. This helps others who have the same problem !
    C# to VB.NET: http://www.developerfusion.com/tools/convert/csharp-to-vb/
    • Marked as answer by Alex Liang Tuesday, July 6, 2010 12:14 PM
    Wednesday, June 30, 2010 8:30 AM
  • Replace the indexof style code and use the path class

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

    It is easier and more sufficient.

     

     


    Success
    Cor
    • Marked as answer by Alex Liang Tuesday, July 6, 2010 12:14 PM
    Wednesday, June 30, 2010 9:13 AM
  • why not use FileInfo Class,  a member of System.IO to get filename, path directory and other file operations instead of LastIndexOf?

    it will save you time and bugs.

    Try replacing your code with this: 

    Private Sub SaveUploadedFile()
        If Request.Files.Count > 0 Then
          Dim pf As HttpPostedFile = Request.Files.Item(0)
          If pf.ContentLength > 0 Then
            Dim srcFile As FileInfo = New FileInfo(pf.FileName)
            Dim strFilename As String = srcFile.Name
            '-- replace spaces with "_" in the filename to make it URL encoding compatable, & with and.
            strFilename = strFilename.Replace(" ", "_").Replace("&", "and")
    
            Dim strTargetFile As String = Path.Combine(srcFile.DirectoryName, strFilename)
            '-- make sure we clear out any existing file before uploading
            If File.Exists(strTargetFile) Then
              DeleteFileOrFolder(strFilename)
            End If
            Try
              pf.SaveAs(strTargetFile)
            Catch ex As Exception
              _FileOperationException = ex
            End Try
          End If
        End If
      End Sub

    Remember to add Imports System.IO at the very  top of your code file.


    Wisdom is of God. James 1:5
    • Marked as answer by Alex Liang Tuesday, July 6, 2010 12:14 PM
    Wednesday, June 30, 2010 7:42 PM
  • sorry but it is not solved yit

    what i found it is

    the URL for this application it is:

    http://filesrv.company.com

    if i open the application from the company network using this URL and try to upload file it give me the above error

    but if i open the application from this URL

    http://filesrv/

    it will upload with no error

    any one have idea about this thing


    Thanks for any help :) my blog is: http://www.waelk.com
    Tuesday, February 15, 2011 1:44 PM