導航:首頁 > 文件教程 > filestream大文件

filestream大文件

發布時間:2022-12-29 22:50:11

㈠ 我需要使用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();
}

閱讀全文

與filestream大文件相關的資料

熱點內容
瘋狂安卓講義第二版代碼 瀏覽:420
老炮兒三小時版本下載 瀏覽:313
matlab怎麼調試程序 瀏覽:2
winxp升級win7的危害 瀏覽:496
網路沒連上卻不可用是怎麼回事 瀏覽:752
社區版本 瀏覽:738
怎麼查微信公眾號什麼時候開通的 瀏覽:717
安裝三菱編程閃退怎麼回事 瀏覽:488
手機怎麼創建word文件格式 瀏覽:694
c語言連接資料庫 瀏覽:887
數據線粉色和白色哪個是正 瀏覽:775
vb編程應注意什麼 瀏覽:855
js循環添加控制項 瀏覽:615
學習計算機網路的作用 瀏覽:235
access資料庫最新內容怎麼調 瀏覽:203
上古世紀新版本跑商 瀏覽:267
iphone5國際漫遊設置 瀏覽:107
ipodwatch如何安裝app 瀏覽:114
誰有微信搶紅包的群號 瀏覽:872
word07頁碼從任意頁開始 瀏覽:791

友情鏈接