【发布时间】:2021-02-13 16:51:47
【问题描述】:
这是我的代码:
public static async void Download()
{
InstagramDownloadMachine instagramDownloadMachine = new InstagramDownloadMachine();
await instagramDownloadMachine.DownloadToPath(@"https://www.insta.com/p/CLL_c2egcL9/", "img.jpg");
}
当我执行它时,我得到这个错误:
System.ArgumentOutOfRangeException: 'StartIndex 不能小于零。 参数名称:startIndex'
(顺便说一句,我使用此代码下载 insta 视频)
所以这是 dll 的完整代码:
private String fileExtension, fileKey;
private const String imgExtension = ".jpg";
private const String videoExtension = ".mp4";
private const String videoKey = "video_url\": \"";
private const String imgKey = "display_url\": \"";
public async Task<Stream> Download(String url)
{
WebRequest request = WebRequest.Create(url);
var response = await request.GetResponseAsync();
Stream dataStream = response.GetResponseStream();
StreamReader reader = new StreamReader(dataStream);
string responseFromServer = reader.ReadToEnd();
string fileUrl = GetFileUrl(responseFromServer);
var fileStream = GetFileStream(fileUrl);
return fileStream;
}
public async Task DownloadToPath(String url, String path)
{
var stream = await Download(url);
MemoryStream memoryStream = new MemoryStream();
stream.CopyTo(memoryStream);
File.WriteAllBytes(path, memoryStream.ToArray());
}
private Stream GetFileStream(String url)
{
HttpWebRequest fileRequest = (HttpWebRequest)WebRequest.Create(url);
var response = fileRequest.GetResponse();
return response.GetResponseStream();
}
private String GetFileUrl(String html)
{
String fileUrl = null;
if (html.Contains("video_url"))
{
fileExtension = videoExtension;
fileKey = videoKey;
}
else
{
fileExtension = imgExtension;
fileKey = imgKey;
}
var auxIndex = html.IndexOf(fileKey);
var partial = html.Substring(auxIndex);
var endOfUrl = partial.IndexOf(fileExtension) + fileExtension.Length;
fileUrl = html.Substring(auxIndex, endOfUrl);
fileUrl = fileUrl.Substring(fileKey.Length);
return fileUrl;
}
}
}
和 idk 错误的 startindex /:
【问题讨论】:
-
还有 1 件事,可以将它用于 xamarin.forms 吗?(有外部 .dll 组件;D
-
我认为这个错误是在 DownloadToPath() 方法中抛出的。如果这是在 DLL 中,那么将很难解决。如果它不在 DLL 中,那么您需要发布它的代码以便我们能够提供帮助。
-
异常的完整堆栈跟踪是什么?
-
添加完整代码
-
顺便说一句,如果可能的话,请使用 HttpClient 而不是手动构造 WebRequests。稍后您会感谢自己的。也无需复制到内存流,然后将所有字节写入文件。打开文件流并复制到该文件流,而不是重复工作