㈠ 我需要使用winform实现大文件(大概20M左右)上传到iis7部署的一个站点,如何实现希望有源码。
我这个可以用,这是我一个上传类里面的上传的方法,20M没问题
using System;
using System.IO;
using System.Threading;
using System.Net;
/// <summary>
/// 文件上传
/// </summary>
/// <param name="filsURL">目标地址</param>
/// <param name="flieName">上传后的文件名</param>
/// <param name="localFile">本地要上传的文件</param>
/// <returns></returns>
public bool FileUpload(string filsURL,string flieName,string localFile)
{
WebClient myWebClient = new WebClient();
Stream postStream = myWebClient.OpenWrite(filsURL+flieName,"PUT");
try
{
myWebClient.Credentials = CredentialCache.DefaultCredentials;//设置网络凭据
// 读取要上传的文件
FileStream fs = new FileStream(localFile, FileMode.Open, FileAccess.Read);
BinaryReader r = new BinaryReader(fs);
//使用UploadFile方法可以用下面的格式
//myWebClient.UploadFile(uriString,"PUT",fileNamePath);
sumLength = fs.Length;
byte[] postArray = r.ReadBytes((int)sumLength);
if(postStream.CanWrite)
{
int k = 1024;
for(int i=0;i<postArray.Length;i+=k)
{
if(i+k>postArray.Length)
{
k = postArray.Length-i;
}
postStream.Write(postArray,i,k);
}
fs.Close();
myWebClient.Dispose();
postStream.Flush();
postStream.Close();
return true;
}
else
{
return false;
}
}
catch(Exception e)
{
return false;
}
}
㈡ C#读写大文件,如何提速
不妨试试下面这个链接的方法
转自http://www.cnblogs.com/criedshy/archive/2010/06/13/1757826.html
C#内存映射文件代码
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Text;
usingSystem.Runtime.InteropServices;
usingSystem.IO;
namespaceTestOpenFileMap
{
publicclassFileMap
{
[StructLayout(LayoutKind.Sequential)]
internalstructSYSTEM_INFO
{
publicuintdwOemId;
publicuintdwPageSize;
;
;
;
;
publicuintdwProcessorType;
;
publicuintdwProcessorLevel;
publicuintdwProcessorRevision;
}
privateconstuintGENERIC_READ=0x80000000;
privateconstuintGENERIC_WRITE=0x40000000;
privateconstintOPEN_EXISTING=3;
privateconstintINVALID_HANDLE_VALUE=-1;
privateconstintFILE_ATTRIBUTE_NORMAL=0x80;
privateconstuintFILE_FLAG_SEQUENTIAL_SCAN=0x08000000;
privateconstuintPAGE_READWRITE=0x04;
privateconstintFILE_MAP_COPY=1;
privateconstintFILE_MAP_WRITE=2;
privateconstintFILE_MAP_READ=4;
///<summary>
///内存映射文件句柄
///</summary>
///<paramname="hFile"></param>
///<paramname="lpFileMappingAttributes"></param>
///<paramname="flProtect"></param>
///<paramname="dwMaximumSizeHigh"></param>
///<paramname="dwMaximumSizeLow"></param>
///<paramname="lpName"></param>
///<returns></returns>
[DllImport("kernel32.dll")]
(IntPtrhFile,
IntPtrlpFileMappingAttributes,uintflProtect,
uintdwMaximumSizeHigh,
uintdwMaximumSizeLow,stringlpName);
///<summary>
///内存映射文件
///</summary>
///<paramname="hFileMappingObject"></param>
///<paramname="dwDesiredAccess"></param>
///<paramname="dwFileOffsetHigh"></param>
///<paramname="dwFileOffsetLow"></param>
///<paramname="dwNumberOfBytesToMap"></param>
///<returns></returns>
[DllImport("kernel32.dll")]
(IntPtrhFileMappingObject,uint
dwDesiredAccess,uintdwFileOffsetHigh,uintdwFileOffsetLow,
uintdwNumberOfBytesToMap);
///<summary>
///撤消文件映像
///</summary>
///<paramname="lpBaseAddress"></param>
///<returns></returns>
[DllImport("kernel32.dll")]
(IntPtrlpBaseAddress);
///<summary>
///关闭内核对象句柄
///</summary>
///<paramname="hObject"></param>
///<returns></returns>
[DllImport("kernel32.dll")]
(IntPtrhObject);
///<summary>
///打开要映射的文件
///</summary>
///<paramname="lpFileName"></param>
///<paramname="dwDesiredAccess"></param>
///<paramname="dwShareMode"></param>
///<paramname="securityAttrs"></param>
///<paramname="dwCreationDisposition"></param>
///<paramname="dwFlagsAndAttributes"></param>
///<paramname="hTemplateFile"></param>
///<returns></returns>
[DllImport("kernel32.dll")]
(stringlpFileName,
uintdwDesiredAccess,FileSharedwShareMode,IntPtrsecurityAttrs,
FileModedwCreationDisposition,uintdwFlagsAndAttributes,IntPtrhTemplateFile);
///<summary>
///得到文件大小
///</summary>
///<paramname="hFile"></param>
///<paramname="highSize"></param>
///<returns></returns>
[DllImport("kernel32.dll",SetLastError=true)]
(IntPtrhFile,outuinthighSize);
///<summary>
///得到系统信息
///</summary>
///<paramname="lpSystemInfo"></param>
[DllImport("kernel32.dll",SetLastError=true)]
(refSYSTEM_INFOlpSystemInfo);
///<summary>
///使用内存文件映射得到文件内容
///</summary>
///<paramname="path">文件路径</param>
///<returns></returns>
(stringpath)
{
StringBuildersb=newStringBuilder();
IntPtrfileHandle=CreateFile(path,
GENERIC_READ|GENERIC_WRITE,FileShare.Read|FileShare.Write,
IntPtr.Zero,FileMode.Open,
FILE_ATTRIBUTE_NORMAL|FILE_FLAG_SEQUENTIAL_SCAN,IntPtr.Zero);
if(INVALID_HANDLE_VALUE!=(int)fileHandle)
{
IntPtrmappingFileHandle=CreateFileMapping(
fileHandle,IntPtr.Zero,PAGE_READWRITE,0,0,"~MappingTemp");
if(mappingFileHandle!=IntPtr.Zero)
{
SYSTEM_INFOsystemInfo=newSYSTEM_INFO();;
GetSystemInfo(refsystemInfo);
//得到系统页分配粒度
uintallocationGranularity=systemInfo.dwAllocationGranularity;
uintfileSizeHigh=0;
//getfilesize
uintfileSize=GetFileSize(fileHandle,outfileSizeHigh);
fileSize|=(((uint)fileSizeHigh)<<32);
//关闭文件句柄
CloseHandle(fileHandle);
uintfileOffset=0;
uintblockBytes=1000*allocationGranularity;
if(fileSize<1000*allocationGranularity)
blockBytes=fileSize;
//分块读取内存,适用于几G的文件
while(fileSize>0)
{
//映射视图,得到地址
IntPtrlpbMapAddress=MapViewOfFile(mappingFileHandle,FILE_MAP_COPY|FILE_MAP_READ|FILE_MAP_WRITE,
(uint)(fileOffset>>32),(uint)(fileOffset&0xFFFFFFFF),
blockBytes);
if(lpbMapAddress==IntPtr.Zero)
{
returnsb;
}
//对映射的视图进行访问
byte[]temp=newbyte[blockBytes];
//从非托管的内存中复制内容到托管的内存中
Marshal.Copy(lpbMapAddress,temp,0,(int)blockBytes);
//用循环太慢了,文件有几M的时候就慢的要死,还是用上面的方法直接
//for(uinti=0;i<dwBlockBytes;i++)
//{
//bytevTemp=Marshal.ReadByte((IntPtr)((int)lpbMapAddress+i));
//temp[i]=vTemp;
//}
//此时用ASCII解码比较快,但有中文会有乱码,用gb2312即ANSI编码也比较快,16M的文件大概4秒就读出来了
//但用unicode解码,文件大的时候会非常慢,会现卡死的状态,不知道为什么?
//ASCIIEncodingencoding=newASCIIEncoding();
//System.Text.UnicodeEncodingencoding=newUnicodeEncoding();
//sb.Append(encoding.GetString(temp));
sb.Append(System.Text.Encoding.GetEncoding("gb2312").GetString(temp));
//撤消文件映像
UnmapViewOfFile(lpbMapAddress);
//修正参数
fileOffset+=blockBytes;
fileSize-=blockBytes;
}
//closefilemappinghandle
CloseHandle(mappingFileHandle);
}
}
returnsb;
}
}
}
㈢ C# 读取文件的问题:file类的ReadAllText、WriteAllText与流Filestream的关系
我们看不到。net Framework 的源代码抄,但猜测ReadAllText()基本上应该也是用Filestream的read方式实现的。多一个方法就可以让你少写很多行的代码,不用处理Filestream的Dispose。这就是写library的人比较聪明之处吧。
当然具体比较两个方法,ReadAllText()是一个简单的方法,你一次读出所有的内容。而直接read Filestream,你有更多的控制,但也需要自己初始化Filestream,记得Dispose FileStream.
简单说吧,ReadAllText()像月票,Read 像每次坐车现买车票。
WriteAllText, 和 Write 方法和前面的一对类似。
㈣ 初学delphi,看到tony的FastFileStream,用于大文件快速读取,但不知如何调用,哪位大侠提供一个示例
这个东西用法跟普通的filesystem差不多,你搜索一下filesystem用法就知道了,比如说从一个文件中第四个字节开始读取8个字节至数组,其它的象seek、write之类的方法也类似于filesystem
var
buffer:array[0..7]ofchar;
f1:TFastFileStream;
begin
f1:=TFastFileStream.Create('e:mongodb-win32-x86_64-2.2.2.zip');
f1.Position:=4;
f1.Read(buffer,sizeof(buffer));
f1.Free;
showmessage('yes');
end;
㈤ C# 将大文件写入网络流的问题。。。
NetStream.Write方法是同步的, 如果对方此时没有Read的时候,则会等待版, 等待达到一定的时间后没有反应, 则发生权异常退出, 所以会有只执行一次的情况发生.
所以在Write之前确认双方已经准备好.
㈥ 在DELPHI中如何用文件流读写几百M大的文件呢
unit U_Client;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, IdBaseComponent, IdComponent, IdTCPConnection, IdTCPClient, Math,
StdCtrls, ComCtrls;
type
Tfrm_Client = class(TForm)
SaveDialog1: TSaveDialog;
IdTCPClient1: TIdTCPClient;
Button1: TButton;
StatusBar1: TStatusBar;
Edit1: TEdit;
Label1: TLabel;
Edit2: TEdit;
Label2: TLabel;
procere Button1Click(Sender: TObject);
private
{ Private declarations }
public
{ Public declarations }
end;
var
frm_Client: Tfrm_Client;
implementation
{$R *.dfm}
procere Tfrm_Client.Button1Click(Sender: TObject);
var
cmd: string;
ASize, TotalSize: Int64;
AFileStream: TFileStream;
begin
IdTCPClient1.Host := Edit1.Text; //连接主机
IdTCPClient1.Port := StrToIntDef(Edit2.Text, 9925); //端口
IdTCPClient1.Connect; //连接
try
IdTCPClient1.WriteLn('BEGIN'); //提示服务器开始接收
cmd := IdTCPClient1.ReadLn;
//以“|”符号分离文件名
SaveDialog1.FileName := Copy(cmd, Pos('|', cmd) + 1, Length(cmd));
if not SaveDialog1.Execute then
begin
IdTCPClient1.WriteLn('CANCEL'); //告诉服务器取消
IdTCPClient1.Disconnect; //断开连接
exit;
end;
TotalSize := StrToInt(Copy(cmd, 0, Pos('|', cmd) - 1)); //分离文件大小
//建立文件流准备接收
AFileStream := TFileStream.Create(SaveDialog1.FileName, fmCreate);
try //循环开始接受
repeat
IdTCPClient1.WriteLn(IntToStr(AFileStream.Size));//发送当前传输的位置
ASize := Min(TotalSize - AFileStream.Size, IdTCPClient1.RecvBufferSize);
//选择剩余大小和缓冲区大小小的一个作为传输的大小
IdTCPClient1.ReadStream(AFileStream, ASize); //接收流
StatusBar1.SimpleText := Format('当前传输位置%d/大小%d', [AFileStream.Size, TotalSize]);
Application.ProcessMessages;
until AFileStream.Size = TotalSize; //大小一致了表示结束
finally
AFileStream.Free; //释放文件流
end;
IdTCPClient1.WriteLn('END'); //提示服务器传输完成
StatusBar1.SimpleText := '传输完成...';
except
StatusBar1.SimpleText := '连接服务器失败或者对方已经中断传输!';
end;
IdTCPClient1.Disconnect;
end;
end.
unit U_Server;
interface
uses
Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
Dialogs, StdCtrls, ComCtrls, IdBaseComponent, IdComponent, IdTCPServer, Math;
type
Tfrm_Server = class(TForm)
IdTCPServer1: TIdTCPServer;
Button1: TButton;
Button2: TButton;
Button3: TButton;
ProgressBar1: TProgressBar;
StatusBar1: TStatusBar;
Edit1: TEdit;
Button4: TButton;
OpenDialog1: TOpenDialog;
Edit2: TEdit;
Label1: TLabel;
Label2: TLabel;
procere Button1Click(Sender: TObject);
procere Button4Click(Sender: TObject);
procere Button2Click(Sender: TObject);
procere Button3Click(Sender: TObject);
procere IdTCPServer1Execute(AThread: TIdPeerThread);
procere FormClose(Sender: TObject; var Action: TCloseAction);
private
AFileStream: TFileStream; //传输的文件流
procere ButtonBegin;
procere ButtonEnd;
{ Private declarations }
public
{ Public declarations }
end;
var
frm_Server: Tfrm_Server;
implementation
{$R *.dfm}
procere Tfrm_Server.Button1Click(Sender: TObject);
begin
if OpenDialog1.Execute then
Edit1.Text := OpenDialog1.FileName;
end;
procere Tfrm_Server.Button4Click(Sender: TObject);
begin
Close;
end;
procere Tfrm_Server.Button2Click(Sender: TObject);
begin
if not FileExists(Edit1.Text) then //检测文件是否存在
begin
Showmessage('文件不存在,请选择文件!');
exit;
end;
//建立文件流
AFileStream := TFileStream.Create(Edit1.Text, fmOpenRead);
ProgressBar1.Max := AFileStream.Size;
ProgressBar1.Position := 0;
ButtonBegin; //VCL开始状态设置
//服务器准备好连接
IdTCPServer1.DefaultPort := StrToIntDef(Edit2.Text, 9925);
if not IdTCPServer1.Active then IdTCPServer1.Active := True;
end;
procere Tfrm_Server.ButtonBegin;
begin //VCL开始状态设置
Button1.Enabled := False;
Button2.Enabled := False;
Button3.Enabled := True;
Button4.Enabled := False;
end;
procere Tfrm_Server.ButtonEnd;
begin //VCL结束状态设置
Button1.Enabled := True;
Button2.Enabled := True;
Button3.Enabled := False;
Button4.Enabled := True;
end;
procere Tfrm_Server.Button3Click(Sender: TObject);
begin
StatusBar1.SimpleText := '传输取消...';
AFileStream.Free; //释放文件流
ButtonEnd; //VCL结束状态设置
end;
procere Tfrm_Server.IdTCPServer1Execute(AThread: TIdPeerThread);
var
cmd: string; //接收到客户端的字符串信息
ASize: Integer; //需要传输的流大小
begin
with AThread.Connection do //已经连街上的一个进程
begin
cmd := UpperCase(ReadLn); //客户端发送的命令字符串
if cmd = 'BEGIN' then //开始传输
begin
//告诉远程传输文件的大小和文件名
WriteLn(Format('%d|%s', [AFileStream.Size, ExtractFileName(Edit1.Text)]));
StatusBar1.SimpleText := '准备传输...';
Exit;
end;
if cmd = 'END' then
begin //传输完成
Button3.Click;
StatusBar1.SimpleText := '传输完成...';
Exit;
end;
if cmd = 'CANCEL' then
begin //传输取消
StatusBar1.SimpleText := '传输取消...';
//保持传输状态
Exit;
end;
//按照指定位置传输文件
AFileStream.Seek(StrToInT(cmd), soFromBeginning); //转到文件流传输的位置
ASize := Min(AFileStream.Size - AFileStream.Position, RecvBufferSize);
//计算需要发送的大小,Min()函数在Math单元
OpenWriteBuffer; //准备发送缓冲
WriteStream(AFileStream, false, false, ASize);
//注意这个函数的参数。
CloseWriteBuffer; //结束发送缓冲
StatusBar1.SimpleText := Format('当前传输位置%s/大小%d', [cmd, AFileStream.Size]);
ProgressBar1.Position := ProgressBar1.Position + ASize;
end;
end;
procere Tfrm_Server.FormClose(Sender: TObject; var Action: TCloseAction);
begin
IdTCPServer1.Active := False;
end;
end.
希望能帮到你!
㈦ 求c#大文件上传解决方案支持分片断点上传
/// <summary>
/// 断点续传,每次调用该方法会从源文件断点续传
/// </summary>
/// <param name="fullName">文件完整路径</param>
private void ReadFile(string fullName)
{
//文件名称
string fileName = Path.GetFileName(fullName);
//保存文件完整路径
string saveFullName = Path.Combine(@"D:\systemInfo", fileName);
FileStream write = new FileStream(saveFullName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite);
FileStream read = File.OpenRead(fullName);// 以读的方式打开
//移动读取流的位置
read.Seek(write.Length, SeekOrigin.Begin);
byte[] bytes = new byte[1024];
int length = 0;
while ((length = read.Read(bytes, 0, bytes.Length)) > 0)
{
write.Write(bytes, 0, length);
}
write.Close();
read.Close();
}