Copy string from a position

Asked

Viewed 4,453 times

1

I have it:

private List<string> _listaCommiter()
        {
            string s = string.Empty;
            string _start = ConfigurationSettings.AppSettings["dir_inicio"];
            List<string> lista = new List<string>();
            List<string> tes = new List<string>();

            string path = ConfigurationSettings.AppSettings["Caminho_Commiter"];

            string[] arquivos = Directory.GetFiles(path, "*", SearchOption.AllDirectories);

            string texto = string.Empty;

            foreach (var item in arquivos)
            {
                s = Path.GetFileNameWithoutExtension(item);
                int _int = item.ToString().IndexOf(_start);
                texto = item.ToString().Substring(_int, item.Length);

                if (!item.Contains("TSNMVC"))
                    lista.Add(s);
            }

            return lista;
        }

The moment I mount the text variable inside the foreach, it gives me this error:

Message=The index and length should refer to a location within the character string. Name of parameter: length

Below the whole error message

System.Argued tofrangeexception was unhandled Hresult=-2146233086 Message=The index and length should refer to a location within the string. Parameter name: length Source=mscorlib
Paramname=length Stacktrace: in System.String.Substring(Int32 startIndex, Int32 length) in Creationextraindo_zip.Form1. _listCommitter() in c: Projects_amil Creationextraindo_zip Creationextraindo_zip Form1.Cs:line 211 in Creatureextraindo_zip.Form1.button1_Click(Object Sender, Eventargs e) in c: Projects_amil Creationextraindo_zip Creationextraindo_zip Form1.Cs:line 240 in System.Windows.Forms.Control.Onclick(Eventargs and) in System.Windows.Forms.Button.Onclick(Eventargs and) in System.Windows.Forms.Button.Onmouseup(Mouseeventargs mevent) in System.Windows.Forms.Control.Wmmouseup(Message& m, Mousebuttons button, Int32 clicks) in System.Windows.Forms.Control.Wndproc(Message& m) in System.Windows.Forms.ButtonBase.Wndproc(Message& m) in System.Windows.Forms.Button.Wndproc(Message& m) in System.Windows.Forms.Control.Controlnativewindow.Onmessage(Message& m) in System.Windows.Forms.Control.Controlnativewindow.Wndproc(Message& m) in System.Windows.Forms.NativeWindow.Debuggablecallback(Intptr hwnd, Int32 msg, Intptr wparam, Intptr lparam) in System.Windows.Forms.UnsafeNativeMethods.Dispatchmessagew(MSG& msg) em System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 Reason, Int32 pvLoopData) in System.Windows.Forms.Application.Threadcontext.Runmessageloopinner(Int32 Reason, Applicationcontext context) in System.Windows.Forms.Application.Threadcontext.Runmessageloop(Int32 Reason, Applicationcontext context) in System.Windows.Forms.Application.Run(Form mainForm) in Creationextraindo_zip.Program.Main() in c: Projects_amil Creationextraindo_zip Creationextraindo_zip Program.Cs:line 19 in System.AppDomain. _nExecuteAssembly(Runtimeassembly Assembly, String[] args) in System.AppDomain.Executeassembly(String assemblyFile, Evidence assemblySecurity, String[] args) in Microsoft.VisualStudio.Hostingprocess.HostProc.Runusersassembly() in System.Threading.Threadhelper.Threadstart_context(Object state) in System.Threading.Executioncontext.Runinternal(Executioncontext executionContext, Contextcallback callback, Object state, Boolean preserverveSyncCtx) in System.Threading.Executioncontext.Run(Executioncontext executionContext, Contextcallback callback, Object state, Boolean preserverveSyncCtx) in System.Threading.Executioncontext.Run(Executioncontext executionContext, Contextcallback callback, Object state) in System.Threading.Threadhelper.Threadstart() Innerexception:

  • In debug, what is inside _int and item before the error?

  • @Ciganomorrisonmendez, _int has the position in which I want to reassemble the new string, which in the first case is 13. Item is an array with the names of the files I want to handle This is correct.

  • Are you sure? If you were, you wouldn’t be making a mistake. Put a breakpoint in texto = item.ToString().Substring(_int, item.Length); and check item by item.

  • When the text arrives = ... I can’t walk anymore, because that’s where the error occurs, but in item yes, it is correct as I said above.

  • There is a tab in Visual Studio called Watch 1. Play the line content there and see what happens.

  • This is the first step of item: C:\Teste_Zip\web\ace\ace003c.asp

  • above this line text = .... , is giving this in watch1: texto = item.ToString().Substring(_int, item.Length); 'item.ToString().Substring(_int, item.Length)' threw an exception of type 'System.ArgumentOutOfRangeException' string

  • I made the hand and gave the same mistake. I did so: string s1 = @"C:\Teste_Zip\web\ace\ace003c.asp";&#xA; int _n = s1.IndexOf(_start);&#xA; string s2 = s1.Substring(_n, s1.Length);

  • On the bottom lines, put _int in a and item in another. See the result.

  • @Ciganomorrisonmendez, I don’t understand what you mean by "bass lines"

  • It worked that way: texto = item.ToString().Substring(_int, item.Length-_int);.

Show 6 more comments

1 answer

3

This error occurs because you are trying to recover a part of the String that does not exist.

Take the case

String item = "0123456789"; // o Length da sua String é 10;
int _int = 3; // inicio da Substring = 3

var texto = item.ToString().Substring(_int, item.Length);

When you do that you’re removing the part of String starting at position 3 and ending at position 10, which is the result of String would be somewhere between 3rd and 13th position of the String, but your String has only 10 positions.

Soon you’ll have the message

Message=The index and length should refer to a location within the character string. Name of parameter: length

using System;

 public class Sample
 {
    public static void Main () {
       Cordas myString = "abc";
       bool test1 = myString.Substring (2, 1) .Equals ( "C"); // Isso é verdade.
       Console.WriteLine (test1);
       bool test2 = String.IsNullOrEmpty (myString.Substring (3, 0)); // Isso é verdade.
       Console.WriteLine (test2);
       try {
          cadeia str3 = myString.Substring (3, 1); // Isto lança ArgumentOutOfRangeException.
          Console.WriteLine (str3);
       }
       catch (ArgumentOutOfRangeException e) {
          Console.WriteLine (e.Message);
       }         
    }
 }
 // O exemplo mostra o seguinte resultado:
 // Verdade
 // Verdade
 // Índice e comprimento devem se referir a um local dentro da cadeia.
 // Nome do parâmetro: comprimento

More Details Here.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.