gpt4 book ai didi

c# - WebDav 409 错误

转载 作者:行者123 更新时间:2023-11-30 22:34:33 25 4
gpt4 key购买 nike

我正在尝试使用 WebDav 添​​加多个文件。我尝试上传到的目录是空的。

我循环遍历文件并发送文件。

1 使用 HTTP Put 将 doc1.txt 添加到 WebDav 服务器 -- 即使文件已经存在,也总是成功。

2 使用 HTTP Put 添加 doc2.txt 到 WebDav 服务器 -- 总是以 409 错误失败。

无论我处理什么文件或顺序,它总是在第二个文件上失败。有人有想法吗?

这是我使用的方法:

public static bool UploadFile(string url, string filePath)
{
if (!File.Exists(filePath))
{
return false;
}

long fileLen = new FileInfo(filePath).Length;

HttpWebRequest Request = (HttpWebRequest)HttpWebRequest.Create(url);

Request.Credentials = mCredentials;
Request.Method = WebRequestMethods.Http.Put;

Request.ContentLength = fileLen;
Request.SendChunked = true;

// Specify that overwriting the destination is allowed.
Request.Headers.Add(@"Overwrite", @"T");
Request.AllowWriteStreamBuffering = true;

System.IO.Stream stream = Request.GetRequestStream();

FileStream fileStrem = new FileStream(filePath, FileMode.Open, FileAccess.Read);

int transferRate = 4096;
byte[] data = new byte[transferRate];
int read = 0;
long totalRead = 0;

try
{
do
{
read = fileStrem.Read(data, 0, data.Length);
if (read > 0)
{
totalRead += read;
stream.Write(data, 0, read);
}
} while (read > 0);
}
catch (Exception ex)
{
throw ex;
}
finally
{
stream.Close();
stream.Dispose();
stream = null;

fileStrem.Close();
fileStrem.Dispose();
fileStrem = null;
}

HttpWebResponse Response;
try
{
Response = (HttpWebResponse)Request.GetResponse();
}
catch (WebException e)
{
if (e.Response == null)
{
Debug.WriteLine("Error accessing Url " + url);
throw;
}

HttpWebResponse errorResponse = (HttpWebResponse)e.Response;

//if the file has not been modified
if (errorResponse.StatusCode == HttpStatusCode.NotModified)
{
e.Response.Close();
return false;
}
else
{
e.Response.Close();
Debug.WriteLine("Error accessing Url " + url);
throw;
}
}
//This case happens if no lastmodedate was specified, but the specified
//file does exist on the server.
Response.Close();

if (totalRead == fileLen)
{
return true;
}
else
{
return false;
}
}

最佳答案

这是我犯的一个愚蠢的错误。 WebDave 文档说,“如果 PUT 导致创建资源而没有适当范围的父集合,则必须失败并返回 409(冲突)。”

好吧,我正在遍历我的文件并连接文件名,而不是仅仅替换文件名。

这就是我调用 UploadFile 的方式:

string url = "http://someurl"

foreach (string file in files)
{
url = url.TrimEnd(new char[] { '/' }) + @"/" + System.IO.Path.GetFileName(file);
UploadFile(url, file);
fileCount++;
}

当我把它改成这个时,它起作用了:

string url = "http://someurl"
string temp;

foreach (string file in files)
{
temp = url.TrimEnd(new char[] { '/' }) + @"/" + System.IO.Path.GetFileName(file);
UploadFile(temp, file);
fileCount++;
}

关于c# - WebDav 409 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7780264/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com