本文整理汇总了C#中System.IO.FileStream.Flush方法的典型用法代码示例。如果您正苦于以下问题:C# System.IO.FileStream.Flush方法的具体用法?C# System.IO.FileStream.Flush怎么用?C# System.IO.FileStream.Flush使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.FileStream
的用法示例。
在下文中一共展示了System.IO.FileStream.Flush方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: Dump
public static void Dump(string fileName, byte[] bytes)
{
System.IO.FileStream s = new System.IO.FileStream(fileName, System.IO.FileMode.OpenOrCreate);
s.Write(bytes, 0, bytes.Length);
s.Flush();
s.Close();
}
示例2: RenderGIF
public void RenderGIF()
{
QREncoderMatrix matrix = QREncoderMatrix.Encode("www.sl.com/BMW-Z3", QRCorrectionLevel.H);
using (System.IO.FileStream stream = new System.IO.FileStream("BMW-Z3.gif", System.IO.FileMode.Create))
{
matrix.ToGIF(stream, scale: NFX.Media.TagCodes.QR.QRImageRenderer.ImageScale.Scale4x);
stream.Flush();
}
}
示例3: RenderBMP
public void RenderBMP()
{
QREncoderMatrix matrix = QREncoderMatrix.Encode("ABCDEF", QRCorrectionLevel.H);
using (System.IO.FileStream stream = new System.IO.FileStream("ABCDEF.bmp", System.IO.FileMode.Create))
{
matrix.ToBMP(stream, scale: NFX.Media.TagCodes.QR.QRImageRenderer.ImageScale.Scale4x);
stream.Flush();
}
}
示例4: 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);
}
示例5: Upload
private const string Upext = "txt,rar,zip,jpg,jpeg,gif,png,swf,wmv,avi,wma,mp3,mid"; // 上传扩展名
#endregion Fields
#region Methods
public JsonResult Upload()
{
var immediate = Request.QueryString["immediate"];//立即上传模式,仅为演示用
byte[] fileBytes;
var disposition = Request.ServerVariables["HTTP_CONTENT_DISPOSITION"];
string localname;
if (disposition != null)
{
fileBytes = Request.BinaryRead(Request.TotalBytes);
localname = Regex.Match(disposition, "filename=\"(.+?)\"").Groups[1].Value;// 读取原始文件名
}
else
{
var postedfile = Request.Files.Get(Inputname);
if (postedfile == null || postedfile.ContentLength <= 0)
return new NewtonsoftJsonResult() { Data = new { err = "无数据提交", msg = "无数据提交!" } };
fileBytes = new byte[postedfile.ContentLength];
postedfile.InputStream.Read(fileBytes, 0, postedfile.ContentLength);
localname = postedfile.FileName;
}
var extension = GetFileExt(localname);
//在小校验
if (fileBytes.Length > Maxattachsize)
{
var err = "文件大小不能超过" + ((double)Maxattachsize / (1024*1024)).ToString("#0.00") + "M";
return new NewtonsoftJsonResult() { Data = new { err, msg = err } };
}
//扩展校验
if (("," + Upext + ",").IndexOf("," + extension + ",", System.StringComparison.CurrentCultureIgnoreCase) < 0)
{
var err = "上传文件扩展名必需为:" + Upext;
return new NewtonsoftJsonResult() { Data = new { err, msg = err } };
}
// 生成随机文件名
var random = new Random(DateTime.Now.Millisecond);
var folder = CreateFolder();
var newFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + random.Next(10000) + "." + extension;
var fullPath = System.IO.Path.Combine(folder, newFileName);
try
{
using (var fs = new System.IO.FileStream(Server.MapPath(fullPath), System.IO.FileMode.Create, System.IO.FileAccess.Write))
{
fs.Write(fileBytes, 0, fileBytes.Length);
fs.Flush();
}
}
catch (Exception e)
{
return new NewtonsoftJsonResult() { Data = new { err = e.Message, msg = e.Message } };
}
return new NewtonsoftJsonResult { Data = new { err = "", msg = new { url = fullPath, localname, id = "1" } } };
}
示例6: SaveFile
public static void SaveFile()
{
try
{
System.IO.FileStream stream = new System.IO.FileStream("\\lastfiles.dat", System.IO.FileMode.Create);
System.Runtime.Serialization.Formatters.Binary.BinaryFormatter formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();
formatter.Serialize( stream, recentProjects );
formatter.Serialize( stream, recentFiles );
stream.Flush();
stream.Close();
}
catch{}
}
示例7: SaveHttpPostFile
/// <summary>
/// 保存上传的文件
/// </summary>
/// <param name="postFileBase"></param>
/// <param name="path"></param>
/// <returns></returns>
private File SaveHttpPostFile(HttpPostedFileBase postFileBase,string path)
{
System.IO.Stream uploadStream = null;
System.IO.FileStream fs = null;
File file = new File();
try
{
uploadStream = postFileBase.InputStream;
int bufferLen = 1024;
byte[] buffer = new byte[bufferLen];
int contentLen = 0;
file.Name = System.IO.Path.GetFileName(postFileBase.FileName);
file.ContentType = postFileBase.ContentType;
file.RealPath = path + Guid.NewGuid().ToString();
fs = new System.IO.FileStream(file.RealPath, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite);
while ((contentLen = uploadStream.Read(buffer, 0, bufferLen)) != 0)
{
fs.Write(buffer, 0, bufferLen);
fs.Flush();
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (null != fs)
{
fs.Close();
}
if (null != uploadStream)
{
uploadStream.Close();
}
}
file.Size = GetFileSize(file.RealPath);
file.Md5 = Md5Util.GetMD5HashFromFile(file.RealPath);
return file;
}
示例8: Insert
public static void Insert(UpgradePackage UpgradePackage)
{
try
{
// 存DB
if ((int)FreightForwarder.Common.PackageSavingType.DB == UpgradePackage.SavingType)
{
(new PackageBusinesses()).AddUpgradePackage(UpgradePackage);
}
else
{
string folder = System.Web.HttpContext.Current.Server.MapPath("~/packages");
string filename = System.IO.Path.Combine(folder, UpgradePackage.FileName);
System.IO.FileStream fs = new System.IO.FileStream(filename, System.IO.FileMode.Create, System.IO.FileAccess.Write);
fs.Write(UpgradePackage.FileBytes, 0, UpgradePackage.FileBytes.Length);
fs.Flush();
fs.Close();
string configfile = System.Web.HttpContext.Current.Server.MapPath("~/upgrade-packages.xml");
//XmlDocument doc = XMLHelper.xmlDoc(configfile);
XmlDocument doc = new XmlDocument();
doc.Load(configfile);
XmlNode pcnode = doc.SelectSingleNode("Packages/PackageCollection");
pcnode.AppendChild(UpgradePackage.ToXmlElement(doc));
doc.Save(configfile);
//XmlNodeList partlistNode = assistXml.SelectNodes("Assist/PartCollection/Part");
//foreach (XmlNode node in partlistNode)
//{
// Part part = new Part();
// part.FromXmlNode(node);
// Parts.Add(part);
//}
}
}
catch (Exception ex)
{
throw ex;
}
}
示例9: WriteBytes
private static void WriteBytes(System.IO.FileInfo aFile, long size)
{
System.IO.Stream stream = null;
try
{
stream = new System.IO.FileStream(aFile.FullName, System.IO.FileMode.Create);
for (int i = 0; i < size; i++)
{
stream.WriteByte((byte) Byten(i));
}
stream.Flush();
}
finally
{
if (stream != null)
{
stream.Close();
}
}
}
示例10: CopyDatabase
private void CopyDatabase(string dataBaseName)
{
var dbPath = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), dataBaseName);
if (!System.IO.File.Exists(dbPath))
{
var dbAssetStream = Assets.Open(dataBaseName);
var dbFileStream = new System.IO.FileStream(dbPath, System.IO.FileMode.OpenOrCreate);
var buffer = new byte[1024];
int b = buffer.Length;
int length;
while ((length = dbAssetStream.Read(buffer, 0, b)) > 0)
{
dbFileStream.Write(buffer, 0, length);
}
dbFileStream.Flush();
dbFileStream.Close();
dbAssetStream.Close();
}
}
示例11: WriteModifications
private void WriteModifications(string dataHistoryFile, IIntegrationResult result)
{
System.IO.FileStream fs = new System.IO.FileStream( dataHistoryFile, System.IO.FileMode.Append);
fs.Seek(0, System.IO.SeekOrigin.End);
System.IO.StreamWriter sw = new System.IO.StreamWriter(fs);
System.Xml.XmlTextWriter currentBuildInfoWriter = new System.Xml.XmlTextWriter(sw);
currentBuildInfoWriter.Formatting = System.Xml.Formatting.Indented;
currentBuildInfoWriter.WriteStartElement("Build");
WriteXMLAttributeAndValue(currentBuildInfoWriter, "BuildDate", Util.DateUtil.FormatDate(result.EndTime));
WriteXMLAttributeAndValue(currentBuildInfoWriter, "Success", result.Succeeded.ToString(CultureInfo.CurrentCulture));
WriteXMLAttributeAndValue(currentBuildInfoWriter, "Label", result.Label);
if (result.Modifications.Length > 0)
{
currentBuildInfoWriter.WriteStartElement("modifications");
for (int i = 0; i < result.Modifications.Length; i++)
{
result.Modifications[i].ToXml(currentBuildInfoWriter);
}
currentBuildInfoWriter.WriteEndElement();
}
currentBuildInfoWriter.WriteEndElement();
sw.WriteLine();
sw.Flush();
fs.Flush();
sw.Close();
fs.Close();
}
示例12: ExtractConfig
private void ExtractConfig( )
{
this.LogDebug ( "Extracting configuration file" );
if ( this.InvokeRequired ) {
this.Invoke ( new SetControlTextDelegate ( SetControlText ), status, "Extracting Configuration File" );
} else {
SetControlText ( status, "Extracting Configuration File" );
}
System.IO.FileInfo config = new System.IO.FileInfo ( System.IO.Path.Combine ( CommandRunner.Instance.TempDataPath, "BareBonesBackup.config" ) );
using ( System.IO.FileStream fs = new System.IO.FileStream ( config.FullName, System.IO.FileMode.Create, System.IO.FileAccess.Write ) ) {
byte[] bytes = Encoding.Default.GetBytes ( Properties.Resources.BareBonesBackup_config );
fs.Write ( bytes, 0, bytes.Length );
fs.Flush ( );
}
}
示例13: FileDow
/// <summary>
/// 下载文件
/// </summary>
public void FileDow(string DBFullName, string FullName)
{
string FileName = System.IO.Path.GetFileName(FullName);
string CFolder = System.IO.Path.GetDirectoryName(FullName);
string DBFolder = System.IO.Path.GetDirectoryName(DBFullName);
// 准备本地目录
if (!System.IO.Directory.Exists(CFolder))
{
System.IO.Directory.CreateDirectory(CFolder);
}
// 1.写入数据库
Apq.Data.Common.DbConnectionHelper.Open(Connection);
System.Data.Common.DbCommand sqlCmd = Connection.CreateCommand();
sqlCmd.CommandText = "Apq_FileTrans_Insert_ADO";
sqlCmd.CommandType = CommandType.StoredProcedure;
Apq.Data.Common.DbCommandHelper cmdHelper = new Apq.Data.Common.DbCommandHelper(sqlCmd);
cmdHelper.AddParameter("@FullName", DBFullName);
cmdHelper.AddParameter("@CFolder", CFolder);
cmdHelper.AddParameter("@ID", 0);
sqlCmd.Parameters["@ID"].Direction = ParameterDirection.InputOutput;
sqlCmd.ExecuteNonQuery();
int ID = Apq.Convert.ChangeType<int>(sqlCmd.Parameters["@ID"].Value);
// 2.读取到本地
DataSet ds = new DataSet();
Apq.Data.Common.DbConnectionHelper connHelper = new Apq.Data.Common.DbConnectionHelper(Connection);
DbDataAdapter da = connHelper.CreateAdapter();
da.SelectCommand.CommandText = "Apq_FileTrans_List";
da.SelectCommand.CommandType = CommandType.StoredProcedure;
Apq.Data.Common.DbCommandHelper daHelper = new Apq.Data.Common.DbCommandHelper(da.SelectCommand);
daHelper.AddParameter("@ID", ID);
da.Fill(ds);
// 3.保存文件
if (ds.Tables.Count > 0 && ds.Tables[0].Rows.Count > 0)
{
byte[] bFile = Apq.Convert.ChangeType<byte[]>(ds.Tables[0].Rows[0]["FileStream"]);
System.IO.FileStream fs = new System.IO.FileStream(FullName, System.IO.FileMode.Create);
fs.Write(bFile, 0, bFile.Length);
fs.Flush();
fs.Close();
}
// 4.删除数据库行
da.SelectCommand.CommandText = "Apq_FileTrans_Delete";
da.SelectCommand.ExecuteNonQuery();
}
示例14: CombineParts
//================== Сортировки ====================
/// <summary>
/// Слияние двух участков одной ячейки первого (он в младшей индексной части) и второго, следующего за ним.
/// Результирующий массив начинается с начала первого участка. Слияние производится сравнением объектных значений
/// элементов посредством функции сравнения ComparePO
/// </summary>
/// <param name="tel">Тип элемента последовательности</param>
/// <param name="off1">offset начала первого участка</param>
/// <param name="number1">длина первого участка</param>
/// <param name="off2">offset начала второго участка</param>
/// <param name="number2">длина второго участка</param>
/// <param name="comparePO">Функция сравнения объектных представлений элементов</param>
internal void CombineParts(PType tel, long off1, long number1, long off2, long number2, Func<object, object, int> comparePO)
{
long pointer_out = off1;
long pointer_in = off2;
int size = tel.HeadSize;
// Используем временный файл
string tmp_fname = null; //MachineInfo.pathForTmp + "tmp_merge.pac";
int last_slash = _filePath.LastIndexOfAny(new char[] { '/', '\\' });
if (last_slash == -1) tmp_fname = "C:/tmp/tmp_merge.pac";
else tmp_fname = _filePath.Substring(0, last_slash + 1) + "tmp_merge.pac";
System.IO.FileStream tmp_fs = new System.IO.FileStream(tmp_fname, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite);
System.IO.BinaryReader tmp_br = new System.IO.BinaryReader(tmp_fs);
// Перепишем number1 * size байтов от начальной точки во временный файл (Первую часть)
this.SetOffset(pointer_out);
long bytestocopy = number1 * size;
int buffLen = 8192;
byte[] buff = new byte[buffLen * size];
while (bytestocopy > 0)
{
int nb = bytestocopy < buff.Length ? (int)bytestocopy : buff.Length;
this.fs.Read(buff, 0, nb);
tmp_fs.Write(buff, 0, nb);
bytestocopy -= nb;
}
tmp_fs.Flush();
// теперь будем сливать массивы
long cnt1 = 0; // число переписанных элементов первой подпоследовательности
long cnt2 = 0; // число переписанных элементов второй подпоследовательности
tmp_fs.Position = 0L; // Установка начальной позиции в файле
this.SetOffset(pointer_in); // Установка на начало второй части последовательности в ячейке
System.IO.Stream fs1 = tmp_fs; // Первый поток
System.IO.Stream fs2 = this.fs; // Второй поток
// Микробуфера для элементов
byte[] m_buf1 = new byte[size];
byte[] m_buf2 = new byte[size];
// Заполнение микробуферов
fs1.Read(m_buf1, 0, size);
fs2.Read(m_buf2, 0, size);
pointer_in += size;
// Это чтобы читать P-значения
System.IO.BinaryReader m_reader1 = new System.IO.BinaryReader(new System.IO.MemoryStream(m_buf1));
System.IO.BinaryReader m_reader2 = new System.IO.BinaryReader(new System.IO.MemoryStream(m_buf2));
// Текущие объекты
object val1 = PaCell.GetPO(tel, m_reader1);
object val2 = PaCell.GetPO(tel, m_reader2);
// Писать будем в тот же буффер buff, текущее место записи:
int ind_buff = 0;
// Слияние!!!
while (cnt1 < number1 && cnt2 < number2)
{
if (comparePO(val1, val2) < 0)
{ // Продвигаем первую подпоследовательность
Buffer.BlockCopy(m_buf1, 0, buff, ind_buff, size);
cnt1++;
if (cnt1 < number1) // Возможен конец
{
fs1.Read(m_buf1, 0, size);
m_reader1.BaseStream.Position = 0;
val1 = PaCell.GetPO(tel, m_reader1);
}
}
else
{ // Продвигаем вторую последовательность
Buffer.BlockCopy(m_buf2, 0, buff, ind_buff, size);
cnt2++;
if (cnt2 < number2) // Возможен конец
{
this.SetOffset(pointer_in); // Установка на текущее место чтения !!!!!!!!!
fs2.Read(m_buf2, 0, size);
pointer_in += size;
m_reader2.BaseStream.Position = 0;
val2 = PaCell.GetPO(tel, m_reader2);
}
}
ind_buff += size;
// Если буфер заполнился, его надо сбросить
if (ind_buff == buff.Length)
{
this.SetOffset(pointer_out);
int volume = ind_buff;
this.fs.Write(buff, 0, volume);
//.........这里部分代码省略.........
示例15: Sync
public override void Sync(System.String name)
{
EnsureOpen();
System.IO.FileInfo fullFile = new System.IO.FileInfo(System.IO.Path.Combine(directory.FullName, name));
bool success = false;
int retryCount = 0;
System.IO.IOException exc = null;
while (!success && retryCount < 5)
{
retryCount++;
System.IO.FileStream file = null;
try
{
try
{
file = new System.IO.FileStream(fullFile.FullName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write, System.IO.FileShare.ReadWrite);
//TODO
// {{dougsale-2.4}}:
//
// in Lucene (Java):
// file.getFD().sync();
// file is a java.io.RandomAccessFile
// getFD() returns java.io.FileDescriptor
// sync() documentation states: "Force all system buffers to synchronize with the underlying device."
//
// what they try to do here is get ahold of the underlying file descriptor
// for the given file name and make sure all (downstream) associated system buffers are
// flushed to disk
//
// how do i do that in .Net? flushing the created stream might inadvertently do it, or it
// may do nothing at all. I can find references to the file HANDLE, but it's not really
// a type, simply an int pointer.
//
// where is FSDirectory.Sync(string name) called from - if this isn't a new feature but rather a refactor, maybe
// i can snip the old code from where it was re-factored...
file.Flush();
success = true;
}
finally
{
if (file != null)
file.Close();
}
}
catch (System.IO.IOException ioe)
{
if (exc == null)
exc = ioe;
try
{
// Pause 5 msec
System.Threading.Thread.Sleep(new System.TimeSpan((System.Int64) 10000 * 5));
}
catch (System.Threading.ThreadInterruptedException ie)
{
// In 3.0 we will change this to throw
// InterruptedException instead
SupportClass.ThreadClass.Current().Interrupt();
throw new System.SystemException(ie.ToString(), ie);
}
}
}
if (!success)
// Throw original exception
throw exc;
}