本文整理汇总了C#中System.IO.FileStream.Dispose方法的典型用法代码示例。如果您正苦于以下问题:C# System.IO.FileStream.Dispose方法的具体用法?C# System.IO.FileStream.Dispose怎么用?C# System.IO.FileStream.Dispose使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.FileStream
的用法示例。
在下文中一共展示了System.IO.FileStream.Dispose方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: FileToByteArray
public byte[] FileToByteArray(string _FileName)
{
byte[] _Buffer = null;
try
{
// Open file for reading
System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
// attach filestream to binary reader
System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream);
// get total byte length of the file
long _TotalBytes = new System.IO.FileInfo(_FileName).Length;
// read entire file into buffer
_Buffer = _BinaryReader.ReadBytes((Int32)(_TotalBytes));
// close file reader
_FileStream.Close();
_FileStream.Dispose();
_BinaryReader.Close();
}
catch (Exception _Exception)
{
// Error
Console.WriteLine("Exception caught in process: {0}", _Exception.ToString());
}
return _Buffer;
}
示例2: Test
public override void Test()
{
OpenDMS.Storage.Providers.EngineRequest request = new OpenDMS.Storage.Providers.EngineRequest();
request.Engine = _engine;
request.Database = _db;
request.OnActionChanged += new EngineBase.ActionDelegate(EngineAction);
request.OnProgress += new EngineBase.ProgressDelegate(Progress);
request.OnComplete += new EngineBase.CompletionDelegate(Complete);
request.OnTimeout += new EngineBase.TimeoutDelegate(Timeout);
request.OnError += new EngineBase.ErrorDelegate(Error);
request.AuthToken = _window.Session.AuthToken;
request.RequestingPartyType = OpenDMS.Storage.Security.RequestingPartyType.User;
Clear();
OpenDMS.Storage.Providers.CreateResourceArgs resourceArgs = new CreateResourceArgs()
{
VersionArgs = new CreateVersionArgs()
};
resourceArgs.Metadata = new OpenDMS.Storage.Data.Metadata();
resourceArgs.Tags = new List<string>();
resourceArgs.Tags.Add("Tag1");
resourceArgs.Tags.Add("Tag2");
resourceArgs.Title = "Test resource";
resourceArgs.VersionArgs.Extension = "txt";
resourceArgs.VersionArgs.Metadata = new OpenDMS.Storage.Data.Metadata();
System.IO.FileStream fs = new System.IO.FileStream("testdoc.txt", System.IO.FileMode.Create, System.IO.FileAccess.Write, System.IO.FileShare.None, 8192, System.IO.FileOptions.None);
byte[] bytes = System.Text.Encoding.ASCII.GetBytes("This is a test content file.");
fs.Write(bytes, 0, bytes.Length);
fs.Flush();
fs.Close();
fs.Dispose();
fs = new System.IO.FileStream("testdoc.txt", System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None, 8192, System.IO.FileOptions.None);
System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();
byte[] data = md5.ComputeHash(fs);
string output = "";
fs.Close();
md5.Dispose();
fs.Dispose();
for (int i = 0; i < data.Length; i++)
output += data[i].ToString("x2");
resourceArgs.VersionArgs.Md5 = output;
resourceArgs.VersionArgs.Content = new OpenDMS.Storage.Data.Content(bytes.Length, new OpenDMS.Storage.Data.ContentType("text/plain"), "testdoc.txt");
WriteLine("Starting CreateNewResource test...");
_start = DateTime.Now;
_engine.CreateNewResource(request, resourceArgs);
}
示例3: ConfigurationServer
public ConfigurationServer()
{
this.WorkflowData = null;
InitializeComponent();
XmlSerializer mySerializer = new XmlSerializer(typeof(WorkflowData));
// To read the file, create a FileStream.
System.IO.FileStream myFileStream = new System.IO.FileStream("workflowdata.xml", System.IO.FileMode.Open);
// Call the Deserialize method and cast to the object type.
this.WorkflowData = (WorkflowData)mySerializer.Deserialize(myFileStream);
myFileStream.Close();
myFileStream.Dispose();
}
示例4: GetBytesFromFile
public static byte[] GetBytesFromFile(string file)
{
try
{
// check if this is a file name;
if (file == null)
return null;
if (file.Trim().Length == 0)
return null;
// get the size of the buffer
int bufferSize = (int)(new System.IO.FileInfo(file).Length);
// check if the file has anything.
if (bufferSize == 0)
return null;
// create the buffer with the proper size
byte[] buffer = new byte[bufferSize];
// create the stream
System.IO.FileStream fs = new System.IO.FileStream(file, System.IO.FileMode.Open);
// create the reader of the stream
System.IO.BinaryReader reader = new System.IO.BinaryReader(fs);
// populate the buffer
buffer = reader.ReadBytes(bufferSize);
// Close the stream
fs.Close();
fs.Dispose();
// close the reader
reader.Close();
fs.Dispose();
return buffer;
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show("Please Make sure that the file is valid or is not in use. Details:\r\n" + ex.Message);
return null;
}
}
示例5: SerializationTest
public virtual void SerializationTest()
{
int TEST_SET_LENGTH = 10;
int[] indicies = SetGenerator.GetRandomArray(TEST_SET_LENGTH);
RLEBitset actual = (RLEBitset)CreateSetFromIndices(indicies, TEST_SET_LENGTH);
System.IO.FileStream fileWriter = new System.IO.FileStream(@"C:\Development\RLE.bin", System.IO.FileMode.Create);
actual.Serialize(fileWriter);
fileWriter.Close();
fileWriter.Dispose();
System.IO.FileStream fileReader = new System.IO.FileStream(@"C:\Development\RLE.bin", System.IO.FileMode.Open);
RLEBitset expected = RLEBitset.Deserialize(fileReader);
fileReader.Close();
fileReader.Dispose();
Assert.AreEqual(actual, expected);
}
示例6: FileToByteArray
public static byte[] FileToByteArray(string _FileName)
{
byte[] _Buffer = null;
try
{
// Open file for reading
System.IO.FileStream _FileStream = new System.IO.FileStream(_FileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.BinaryReader _BinaryReader = new System.IO.BinaryReader(_FileStream);
long _TotalBytes = new System.IO.FileInfo(_FileName).Length;
_Buffer = _BinaryReader.ReadBytes((Int32)_TotalBytes);
_FileStream.Close();
_FileStream.Dispose();
_BinaryReader.Close();
}
catch
{
//
}
return _Buffer;
}
示例7: PutFile
private static string PutFile(string remotefile,string localfile)
{
string sReturn = "";
try
{
System.IO.FileStream InputBin = new System.IO.FileStream(localfile, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.None);
try
{
System.Net.HttpWebRequest request = (System.Net.HttpWebRequest)System.Net.WebRequest.Create(remotefile);
request.Method = "PUT";
request.ContentType = "application/octet-stream";
request.ContentLength = InputBin.Length;
System.IO.Stream dataStream = request.GetRequestStream();
byte[] buffer = new byte[32768];
int read;
while ((read = InputBin.Read(buffer, 0, buffer.Length)) > 0)
{
dataStream.Write(buffer, 0, read);
}
dataStream.Close();
System.Net.HttpWebResponse response = (System.Net.HttpWebResponse)request.GetResponse();
sReturn = response.StatusCode.ToString();
if (sReturn != response.StatusDescription)
sReturn += " " + response.StatusDescription;
response.Close();
}
catch (Exception ex1)
{
sReturn = ex1.Message;
}
InputBin.Close();
InputBin.Dispose();
}
catch (Exception ex2)
{
sReturn = ex2.Message;
}
return sReturn;
}
示例8: Initialize
public static BplusTreeBytes Initialize(string treefileName, string blockfileName, int KeyLength)
{
System.IO.Stream treefile = null;
System.IO.Stream blockfile = null;
try
{
treefile = new System.IO.FileStream(treefileName, System.IO.FileMode.CreateNew, System.IO.FileAccess.ReadWrite);
blockfile = new System.IO.FileStream(blockfileName, System.IO.FileMode.CreateNew, System.IO.FileAccess.ReadWrite);
return Initialize(treefile, blockfile, KeyLength);
}
catch(Exception ex)
{
if(treefile != null)
treefile.Dispose();
if(blockfile != null)
blockfile.Dispose();
throw ex;
}
}
示例9: FileToByteArray
/// <summary>
/// Function to get byte array from a file
/// </summary>
/// <param name="fileName">File name to get byte array</param>
/// <returns>Byte Array</returns>
public static byte[] FileToByteArray(string fileName)
{
byte[] buffer;
// Open file for reading
var fileStream = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read);
// attach filestream to binary reader
using (var binaryReader = new System.IO.BinaryReader(fileStream))
{
var totalBytes = new System.IO.FileInfo(fileName).Length;
// read entire file into buffer
buffer = binaryReader.ReadBytes((Int32)totalBytes);
// close file reader
fileStream.Close();
fileStream.Dispose();
binaryReader.Close();
}
return buffer;
}
示例10: UpdateTzToDB
//.........这里部分代码省略.........
}
else if ((this.tabPage2.Controls[i].Controls.Count > 0) && ((String.Compare(this.tabPage2.Controls[i].Name, "panel45")) != 0))
{
UpdateDBCycle(this.tabPage2.Controls[i], ref cmdName, ref Parameters, ref DataFromTextBox);
}
}
cmdName = cmdName.Remove(cmdName.Length - 1);
cmdName += " WHERE ID_DOC = '" + number + "'";
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
successToLoadData = SQLOracle.UpdateQuery(cmdName, Parameters, DataFromTextBox);
Parameters.Clear();
DataFromTextBox.Clear();
for (int i = 1; i < 10; i++)
{
if (successToLoadData == true)
{
cmdName = "UPDATE USP_TZ_DATA_TP SET NAIM_KOMP = :NAIM_KOMP,OBOZN_KOMP = :OBOZN_KOMP, KOL = :KOL WHERE NUM_PANEL = '" + i.ToString() + "' AND ID_DOC = '" + number +"'";
Parameters.Add("NAIM_KOMP"); DataFromTextBox.Add(PriemSpisanie.IsNullParametr(((TextBox)(this.panel33.Controls.Find(("NAIM_KOMP0" + i.ToString()), true)[0]))));
Parameters.Add("OBOZN_KOMP"); DataFromTextBox.Add(PriemSpisanie.IsNullParametr(((TextBox)(this.panel32.Controls.Find(("OBOZN_KOMP0" + i.ToString()), true)[0]))));
Parameters.Add("KOL"); DataFromTextBox.Add(PriemSpisanie.IsNullParametr(((TextBox)(this.panel34.Controls.Find(("KOL0" + i.ToString()), true)[0]))));
successToLoadData = SQLOracle.UpdateQuery(cmdName, Parameters, DataFromTextBox);
Parameters.Clear();
DataFromTextBox.Clear();
}
}
for (int i = 10; i < 21; i++)
{
if (successToLoadData == true)
{
cmdName = "UPDATE USP_TZ_DATA_TP SET NAIM_KOMP = :NAIM_KOMP,OBOZN_KOMP = :OBOZN_KOMP, KOL = :KOL WHERE NUM_PANEL = '" + i.ToString() + "' AND ID_DOC = '" + number + "'";
Parameters.Add("NAIM_KOMP"); DataFromTextBox.Add(PriemSpisanie.IsNullParametr(((TextBox)(this.panel33.Controls.Find(("NAIM_KOMP" + i.ToString()), true)[0]))));
Parameters.Add("OBOZN_KOMP"); DataFromTextBox.Add(PriemSpisanie.IsNullParametr(((TextBox)(this.panel32.Controls.Find(("OBOZN_KOMP" + i.ToString()), true)[0]))));
Parameters.Add("KOL"); DataFromTextBox.Add(PriemSpisanie.IsNullParametr(((TextBox)(this.panel34.Controls.Find(("KOL" + i.ToString()), true)[0]))));
successToLoadData = SQLOracle.UpdateQuery(cmdName, Parameters, DataFromTextBox);
Parameters.Clear();
DataFromTextBox.Clear();
}
}
if ((BMPIsLoad == 1)||(BMPIsLoad == 3))
if ((this.SCETCH1.Image != null) && (successToLoadData == true))
using (TemporaryFile tempFile = new TemporaryFile())
{
this.SCETCH1.Image.Save(tempFile.FilePath.ToString());
System.IO.FileStream FileStreamSCETCH1 = new System.IO.FileStream(tempFile.FilePath.ToString(), System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[] SCETCH1InByte = new Byte[FileStreamSCETCH1.Length];
FileStreamSCETCH1.Read(SCETCH1InByte, 0, SCETCH1InByte.Length);
FileStreamSCETCH1.Close();
IDisposable disp = (IDisposable)FileStreamSCETCH1;
disp.Dispose();
successToLoadData = SQLOracle.BLOBUpdateQuery(("UPDATE USP_TZ_DATA SET SCETCH1 = :SCETCH1 WHERE ID_DOC = '" + number + "'"), "SCETCH1", SCETCH1InByte);
FileStreamSCETCH1.Dispose();
}
if ((BMPIsLoad == 2) || (BMPIsLoad == 3))
if ((this.SCETCH2.Image != null) && (successToLoadData == true))
using (TemporaryFile tempFile = new TemporaryFile())
{
this.SCETCH2.Image.Save(tempFile.FilePath.ToString());
System.IO.FileStream FileStreamBMP = new System.IO.FileStream(tempFile.FilePath.ToString(), System.IO.FileMode.Open, System.IO.FileAccess.Read);
byte[] BMPInByte = new Byte[FileStreamBMP.Length];
FileStreamBMP.Read(BMPInByte, 0, BMPInByte.Length);
FileStreamBMP.Close();
IDisposable disp = (IDisposable)FileStreamBMP;
disp.Dispose();
successToLoadData = SQLOracle.BLOBUpdateQuery(("UPDATE USP_TZ_DATA SET SCETCH2 = :SCETCH2 WHERE ID_DOC = '" + number + "'"), "SCETCH2", BMPInByte);
FileStreamBMP.Dispose();
}
if (successToLoadData == true)
{
MessageBox.Show("Загрузка прошла успешно!");
}
else
{
MessageBox.Show("Загрузка прошла неудачно!");
}
}
示例11: UploadFile
public string UploadFile(string formItemName, string filePath, Dictionary<string, string> othData)
{
byte[] beginBuff = Encoding.UTF8.GetBytes("------WebKitFormBoundaryQiOnR7KX03DvV4iK\r\n");
byte[] endBuff = Encoding.UTF8.GetBytes("\r\n------WebKitFormBoundaryQiOnR7KX03DvV4iK--\r\n");
byte[] centerEndBuff = Encoding.UTF8.GetBytes("\r\n------WebKitFormBoundaryQiOnR7KX03DvV4iK\r\n");
this.Method = Methods.POST;
InitWebRequest();
this.webRequest.ContentType = "multipart/form-data; boundary=----WebKitFormBoundaryQiOnR7KX03DvV4iK";
//this.webRequest.ContentLength = fs.Length + startBuff.Length + endBuff.Length;
System.IO.Stream stream = webRequest.GetRequestStream();
stream.Write(beginBuff, 0, beginBuff.Length);//Start
foreach (var item in othData)
{
byte[] textStartBuff = Encoding.UTF8.GetBytes(string.Format("Content-Disposition: form-data; name=\"{0}\"\r\n\r\n", item.Key));
stream.Write(textStartBuff, 0, textStartBuff.Length);
byte[] text = Encoding.UTF8.GetBytes(item.Value);
stream.Write(text, 0, text.Length);
stream.Write(centerEndBuff, 0, centerEndBuff.Length);
}
byte[] fileStartBuff = Encoding.UTF8.GetBytes("Content-Disposition: form-data; name=\"" + formItemName + "\"; filename=\"" + System.IO.Path.GetFileName(filePath) + "\"\r\nContent-Type: application/octet-stream\r\n\r\n");
stream.Write(fileStartBuff, 0, fileStartBuff.Length);
byte[] readBuff = new byte[1024];
int len = 0;
System.IO.FileStream fs = new System.IO.FileStream(filePath, System.IO.FileMode.Open);
while ((len = fs.Read(readBuff, 0, readBuff.Length)) > 0)
{
stream.Write(readBuff, 0, len);
}
fs.Close();
fs.Dispose();
stream.Write(endBuff, 0, endBuff.Length);
System.IO.StreamReader reader = new System.IO.StreamReader(webRequest.GetResponse().GetResponseStream());
return reader.ReadToEnd();
}
示例12: Get
// GET /api/music/5
public HttpResponseMessage Get(Guid id, string play)
{
string musicPath = HttpContext.Current.Server.MapPath("~/Content/Music") + "\\" + id.ToString() + ".mp3";
if (System.IO.File.Exists(musicPath))
{
HttpResponseMessage result = new HttpResponseMessage(System.Net.HttpStatusCode.OK);
System.IO.FileStream stream = new System.IO.FileStream(musicPath, System.IO.FileMode.Open);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
ms.SetLength(stream.Length);
stream.Read(ms.GetBuffer(), 0, (int)stream.Length);
ms.Flush();
stream.Close();
stream.Dispose();
result.Content = new StreamContent(ms);
result.Content.Headers.ContentType = new System.Net.Http.Headers.MediaTypeHeaderValue("audio/mpeg");
return result;
}
else
{
return new HttpResponseMessage(System.Net.HttpStatusCode.NotFound);
}
}
示例13: SaveFile
public void SaveFile(UploadFileModel UploadFile, out string strFilePath)
{
// Store File to File System
//string strVirtualPath = System.Configuration.ConfigurationManager.AppSettings["FileUploadLocation"].ToString();//权限系统没有文件路径配置
string strNewFileName = string.Empty;
string strVirtualPath = "/UploadedFiles/";
if (!string.IsNullOrWhiteSpace(UploadFile.FileName))
{
strNewFileName = DateTime.Now.ToString("yyMMddhhmmss") + DateTime.Now.Millisecond.ToString() + UploadFile.FileName.Substring(UploadFile.FileName.LastIndexOf("."));
}
string strPath = System.Web.HttpContext.Current.Server.MapPath(strVirtualPath) + strNewFileName;
if (System.IO.Directory.Exists(System.Web.HttpContext.Current.Server.MapPath(strVirtualPath)) == false)
{
System.IO.Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(strVirtualPath));
}
System.IO.FileStream FileStream = new System.IO.FileStream(strPath, System.IO.FileMode.Create);
FileStream.Write(UploadFile.File, 0, UploadFile.File.Length);
FileStream.Close();
FileStream.Dispose();
strFilePath = strVirtualPath + strNewFileName;
}
示例14: ConvertFile
/// <summary>
/// Convert a file from source codepage to destination codepage
/// </summary>
/// <param name="filename">filename</param>
/// <param name="destDir">output directory</param>
/// <param name="sourceCP">source codepage</param>
/// <param name="destCP">destination codepage</param>
/// <param name="specialType">SpecialTypes</param>
/// <param name="outputMetaTag">True=output meta tag</param>
/// <returns></returns>
public static bool ConvertFile(string filename, string destDir, int sourceCP, int destCP, SpecialTypes specialType, bool outputMetaTag, byte[] BOM)
{
//source file data
string fileData = "";
//get the encodings
Encoding sourceEnc = Encoding.GetEncoding(sourceCP);
Encoding destEnc = Encoding.GetEncoding(destCP);
System.IO.FileStream fw = null;
//get the output filename
//john church 05/10/2008 use directory separator char instead of backslash for linux support
string outputFilename = filename.Substring(filename.LastIndexOf(System.IO.Path.DirectorySeparatorChar) + 1);
//check if the file exists
if (!System.IO.File.Exists(filename))
{
throw new System.IO.FileNotFoundException(filename);
}
try
{
//check or create the output directory
if (!System.IO.Directory.Exists(destDir))
{
System.IO.Directory.CreateDirectory(destDir);
}
//check if we need to output meta tags
if (outputMetaTag)
{
fileData = "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=" + destEnc.WebName + "\" />";
}
//check we've got a backslash at the end of the pathname
//john church 05/10/2008 use directory separator char instead of backslash for linux support
if (destDir.EndsWith(System.IO.Path.DirectorySeparatorChar.ToString()) == false)
destDir += System.IO.Path.DirectorySeparatorChar;
//read in the source file
//john church 09/02/2011 add source encoding parameter to ReadAllText call
fileData += System.IO.File.ReadAllText(filename, sourceEnc);
//check for any special cases
switch (specialType)
{
case SpecialTypes.UnicodeAsDecimal:
fileData = ConvertDecimals(fileData);
break;
case SpecialTypes.None:
//do nothing
break;
}
//put the data into an array
byte[] bSource = sourceEnc.GetBytes(fileData);
//do the conversion
byte[] bDest = System.Text.Encoding.Convert(sourceEnc, destEnc, bSource);
//write out the file
fw = new System.IO.FileStream(destDir + outputFilename, System.IO.FileMode.Create);
if (BOM.Length > 0)
{
fw.Write(BOM, 0, BOM.Length);
}
fw.Write(bDest, 0, bDest.Length);
return true;
}
catch (Exception ex)
{
//just throw the exception back up
throw ex;
}
finally
{
//clean up the stream
if (fw != null)
{
fw.Close();
}
fw.Dispose();
}
}
示例15: saveFileDialog1_FileOk
private void saveFileDialog1_FileOk(object sender, EventArgs e)
{
System.IO.FileStream fs = null;
try
{
fs = new System.IO.FileStream(saveFileDialog1.FileName, System.IO.FileMode.Create);
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter bf = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
bf.Serialize(fs, this.settings);
}
catch
{
MessageBox.Show("Error saving settings.");
}
finally
{
if (fs != null)
fs.Dispose();
}
}