C# System.ArgumentOutOfRangeException:StartIndex不能小于零
我不知道为什么下面的函数对字符串有效,但还是中断了 只是尝试获取传入文件的列表并相应地解析它们。一定有什么明显的东西我遗漏了 我给出了一行代码,它正在进一步分解。发布了整个方法,以防万一C# System.ArgumentOutOfRangeException:StartIndex不能小于零,c#,asp.net,.net,networking,ftp,C#,Asp.net,.net,Networking,Ftp,我不知道为什么下面的函数对字符串有效,但还是中断了 只是尝试获取传入文件的列表并相应地解析它们。一定有什么明显的东西我遗漏了 我给出了一行代码,它正在进一步分解。发布了整个方法,以防万一 public string[] GetFileList() { string[] downloadFiles; StringBuilder result = new StringBuilder(); FtpWebRequest reqFTP;
public string[] GetFileList()
{
string[] downloadFiles;
StringBuilder result = new StringBuilder();
FtpWebRequest reqFTP;
try
{
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/"));
reqFTP.UseBinary = true;
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
reqFTP.Method = WebRequestMethods.Ftp.ListDirectory;
WebResponse response = reqFTP.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream());
//MessageBox.Show(reader.ReadToEnd());
string line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}
在下面的一行中断
result.Remove(result.ToString().LastIndexOf('\n'), 1);
reader.Close();
response.Close();
//MessageBox.Show(response.StatusDescription);
return result.ToString().Split('\n');
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
downloadFiles = null;
return downloadFiles;
}
}
错误名称位于标题中:
System.ArgumentOutOfRangeException:StartIndex不能小于零
删除前检查索引
int index = result.ToString().LastIndexOf('\n');
if(index >=0)
{
result.Remove(index, 1);
}
显然,
result.ToString().LastIndexOf('\n')
返回-1,这意味着没有预期的换行符。