我有数组链接。每个链接都呈现一个XML文件。如何通过一次调用迭代每个XML并将其保存到文件夹。
GetMesssageAttachments(userId)
返回数组6链接,但是当前代码仅保存第一个文件。怎么了谢谢
public async void SaveXMLMessages(string userId)
{
try
{
if (_responseMessage.IsSuccessStatusCode)
{
string messagesFolder = @"C:\XMLMessages";
Directory.CreateDirectory(messagesFolder);
string messageFileName = Path.GetRandomFileName();
string messagesPath = Path.Combine(messagesFolder, messageFileName);
foreach (string xmlMessage in await GetMesssageAttachments(userId))
{
var xmlMessageResponse = await _client.GetAsync(xmlMessage);
using (FileStream fileStream = new FileStream(messagesPath, FileMode.Create))
{
await xmlMessageResponse.Content.CopyToAsync(fileStream);
}
}
}
}
catch (Exception e)
{
throw e.InnerException;
}
}
已更新
这是工作。
public async void SaveXMLMessages(string userId)
{
try
{
if (_responseMessage.IsSuccessStatusCode)
{
string messagesFolder = @"C:\XMLMessages";
Directory.CreateDirectory(messagesFolder);
foreach (string xmlMessage in await GetMesssageAttachments(userId))
{
string messageFileName = Path.GetRandomFileName();
string messagesPath = Path.Combine(messagesFolder, messageFileName);
var xmlMessageResponse = await _client.GetAsync(xmlMessage);
using (FileStream fileStream = new FileStream(messagesPath, FileMode.Create))
{
await xmlMessageResponse.Content.CopyToAsync(fileStream);
}
}
}
}
catch (Exception e)
{
throw e.InnerException;
}
}
答案 0 :(得分:3)
与messagesPath
中使用的foreach
相同。这意味着循环中仅创建一个文件
您必须像这样在循环中重新初始化它:
foreach (string xmlMessage in await GetMesssageAttachments(userId))
{
string messageFileName = Path.GetRandomFileName();
string messagesPath = Path.Combine(messagesFolder, messageFileName);
var xmlMessageResponse = await _client.GetAsync(xmlMessage);
using (FileStream fileStream = new FileStream(messagesPath, FileMode.Create))
{
await xmlMessageResponse.Content.CopyToAsync(fileStream);
}
}
答案 1 :(得分:1)
也许您在每次迭代中都覆盖文件,请尝试将此块移到您的foreach内部:
string messageFileName = Path.GetRandomFileName();
string messagesPath = Path.Combine(messagesFolder, messageFileName);
答案 2 :(得分:1)
'thierry v'代码和rsb55所说的只有很小的变化是正确的。您的代码应如下所示
foreach (string xmlMessage in await GetMesssageAttachments(userId))
{
string messageFileName = Path.GetRandomFileName();
string messagesPath = Path.Combine(messagesFolder, messageFileName);
var xmlMessageResponse = await _client.GetAsync(xmlMessage);
using (FileStream fileStream = new FileStream(messagesPath, FileMode.Create))
{
await xmlMessageResponse.Content.CopyToAsync(fileStream);
}
}