我正在尝试将文件复制到小块大小的Web处理程序中。它在缓冲区相对较大时工作正常,并且总是在图像大小时工作。但是我得到的块大小的图像失真太小了。
当我将相同的字节重新组合在一起时,为什么会改变?
OpenFileDialog o = new OpenFileDialog();
o.ShowDialog();
using (WebClient webClient = new WebClient())
{
int index = 0;
var tmpName = Guid.NewGuid().ToString();
const int chunkSize = 10*1024;
webClient.Headers.Add("Filename", "");
using (var file = o.OpenFile())
{
int bytesRead;
//Using ChunkSize will give image distortion. But file.length works. So does dividing by 10 to result in 10 chunks. Why?
byte[] buffer = new byte[file.Length/10];
int position = 0;
while (position < file.Length)
{
if (position + buffer.Length > file.Length)
{
buffer = new byte[file.Length - position];
}
bytesRead = file.Read(buffer, 0, buffer.Length);
position += bytesRead;
var fileName = string.Format("{0}.{1}.{2}", tmpName, index, o.SafeFileName);
webClient.Headers["Filename"] = fileName;
//webClient.Headers["blockSize"] = buffer.Length.ToString();
webClient.UploadData("http://localhost:49815/FileUpload.ashx", buffer);
index++;
}
}
var values = new NameValueCollection();
values.Add("Filename", string.Format("{0}.{1}", tmpName, o.SafeFileName));
values.Add("Complete", "true");
webClient.Headers.Clear();
webClient.UploadValues("http://localhost:49815/FileUpload.ashx", values);
}
我测试了什么
将分解的文件保存到同一位置会出现同样的问题。所以HTTP与它无关。
private void CombineFiles(string filename)
{
var fileguid = filename.Substring(0, filename.IndexOf(".") + 1);
var shortFileName = filename.Replace(fileguid, "");
var files = Directory.GetFiles(AppDomain.CurrentDomain.BaseDirectory + "images", fileguid + "*");
using (var filestream = File.Create(AppDomain.CurrentDomain.BaseDirectory + "images/" + shortFileName))
{
foreach (string file in files)
{
var fileBuffer = File.ReadAllBytes(file);
filestream.Write(fileBuffer, 0, fileBuffer.Length);
File.Delete(file);
}
}
}
答案 0 :(得分:0)
啊。愚蠢的问题。由于我的命名方案是1,2,3,4,5,6,7,8,9,10,因此文件出现故障。因此当它达到10时,值为1,10,2,3,4 ......
var directory = new DirectoryInfo(AppDomain.CurrentDomain.BaseDirectory + "images");
var files = directory.GetFiles(fileguid + "*").OrderBy(x => x.CreationTime).ToArray();
愚蠢的错误。