本文整理汇总了C#中System.IO.StreamWriter.Flush方法的典型用法代码示例。如果您正苦于以下问题:C# StreamWriter.Flush方法的具体用法?C# StreamWriter.Flush怎么用?C# StreamWriter.Flush使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类System.IO.StreamWriter
的用法示例。
在下文中一共展示了StreamWriter.Flush方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: WriteToStreamAsync
//OnWriteToStreamAsync(Type type, object value, Stream stream, HttpContentHeaders contentHeaders, FormatterContext formatterContext, TransportContext transportContext)
public override Task WriteToStreamAsync(Type type, object value, Stream writeStream, HttpContent content, TransportContext transportContext)
{
string uri = HttpContext.Current.Request.Url.Query;
string method = HttpContext.Current.Request.HttpMethod;
if(HttpContext.Current.Request.HttpMethod =="GET")
{
return Task.Factory.StartNew(() =>
{
var writer = new StreamWriter(writeStream);
var query = HttpUtility.ParseQueryString(uri);
string callback = query[CallbackQueryParameter];
writer.Write(callback + "(");
writer.Flush();
base.WriteToStreamAsync(type, value, writeStream, content, transportContext).Wait();
writer.Write(")");
writer.Flush();
});
}
else
{
return base.WriteToStreamAsync(type, value, writeStream, content, transportContext);
}
}
示例2: Encrypt
public static string Encrypt(string originalString, byte[] key)
{
try
{
if (String.IsNullOrEmpty(originalString))
{
throw new ArgumentNullException
("The string which needs to be encrypted can not be null.");
}
DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
cryptoProvider.Mode = CipherMode.ECB;
cryptoProvider.Padding = PaddingMode.Zeros;
MemoryStream memoryStream = new MemoryStream();
CryptoStream cryptoStream = new CryptoStream(memoryStream,
cryptoProvider.CreateEncryptor(key, key), CryptoStreamMode.Write);
StreamWriter writer = new StreamWriter(cryptoStream);
writer.Write(originalString);
writer.Flush();
cryptoStream.FlushFinalBlock();
writer.Flush();
return Convert.ToBase64String(memoryStream.GetBuffer(), 0, (int)memoryStream.Length);
}
catch (Exception e)
{
return null;
}
}
示例3: ProcessLogQueue
protected override void ProcessLogQueue(ConcurrentQueue<LogEvent> logQueue, LogEventDispatcher dispatcher)
{
// Open a buffered stream writer to the console standard out
LogEvent logEvent;
using (var writer = new StreamWriter(new BufferedStream(Console.OpenStandardOutput())))
{
// Pull all of the log events from the queue and write them to the buffered writer
while (logQueue.IsEmpty == false)
{
if (logQueue.TryDequeue(out logEvent))
{
try
{
writer.Write(Layout.FormatLogEvent(logEvent));
}
catch (Exception e)
{
try
{
writer.Flush();
}
finally
{
if (dispatcher != null)
dispatcher.HandleException(e, logEvent);
else
throw e;
}
}
}
}
writer.Flush();
}
}
示例4: SerializeRequest
public Message SerializeRequest(MessageVersion messageVersion, object[] parameters)
{
MemoryStream outStream = new MemoryStream();
StreamWriter writer = new StreamWriter(outStream);
writer.WriteLine("--" + Boundary);
writer.WriteLine("Content-Disposition: form-data; name=\"torrent_file\"; filename=\"foo.torrent\"");
writer.WriteLine("Content-Type: ");
writer.WriteLine();
writer.Flush();
(parameters[0] as Stream).CopyTo(outStream);
writer.WriteLine();
writer.WriteLine("--" + Boundary + "--");
writer.Flush();
outStream.Seek(0, SeekOrigin.Begin);
parameters[0] = outStream;
Message request = this.originalFormatter.SerializeRequest(messageVersion, parameters);
if (!request.Properties.ContainsKey(HttpRequestMessageProperty.Name))
{
request.Properties[HttpRequestMessageProperty.Name] = new HttpRequestMessageProperty();
}
HttpRequestMessageProperty http = request.Properties[HttpRequestMessageProperty.Name] as HttpRequestMessageProperty;
http.Headers.Set(HttpRequestHeader.ContentType, "multipart/form-data; boundary=" + Boundary);
http.Headers.Remove(HttpRequestHeader.Expect);
return request;
}
示例5: Main
static void Main(string[] args)
{
Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
IPEndPoint iep = new IPEndPoint(IPAddress.Any, 9000);
s.Bind(iep);
s.Listen(10);
Console.WriteLine("Waiting Client...");
Socket sc = s.Accept();
NetworkStream ns = new NetworkStream(sc);
StreamReader sr = new StreamReader(ns);
StreamWriter sw = new StreamWriter(ns);
sw.WriteLine("Chao Client");
sw.Flush();
while (true)
{
string st;
st = sr.ReadLine();
Console.WriteLine("Client gui len:{0}",st);
if (st.ToUpper().Equals("QUIT"))
break;
st = st.ToUpper();
sw.WriteLine(st);
sw.Flush();
}
sw.Close();
sr.Close();
ns.Close();
sc.Close();
s.Close();
}
示例6: IRC
public IRC()
{
//"https://api.twitch.tv/kraken/oauth2/authorize?response_type=token&client_id=" + ConfigurationManager.AppSettings["client_id"] + "&redirect_uri=http://localhost&scope=channel_read+channel_editor+channel_commercial+channel_subscriptions+channel_check_subscription
Client = new TcpClient("irc.twitch.tv", 6667);
NwStream = Client.GetStream();
Reader = new StreamReader(NwStream, Encoding.GetEncoding("iso8859-1"));
Writer = new StreamWriter(NwStream, Encoding.GetEncoding("iso8859-1"));
botUsername = ConfigurationManager.AppSettings["username"];
channel = ConfigurationManager.AppSettings["channel"];
timeoutList = sql.readSQLite("timeoutWords", "name", "duration");
banList = sql.readSQLite("bannedwords", "name");
commandList = sql.readSQLite("commands", "command", "response");
listen = new Thread(new ThreadStart(Listen));
listen.Start();
Writer.WriteLine("PASS " + ConfigurationManager.AppSettings["password"]);
Writer.Flush();
Writer.WriteLine("NICK " + botUsername);
Writer.Flush();
Writer.WriteLine("USER " + botUsername + "8 * :" + botUsername);
Writer.Flush();
Writer.WriteLine("JOIN #" + channel + "\n");
Writer.Flush();
}
示例7: Start
public void Start()
{
DateTime dt = System.DateTime.Now;
bool exists = Directory.Exists("./log");
if (!exists)
Directory.CreateDirectory("./log");
fileName = string.Format("./log/psd{0:D4}{1:D2}{2:D2}-{3:D2}{4:D2}{5:D2}.log",
dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second);
var ass = System.Reflection.Assembly.GetExecutingAssembly().GetName();
int version = ass.Version.Revision;
queue = new BlockingCollection<string>(new ConcurrentQueue<string>());
Task.Factory.StartNew(() =>
{
using (StreamWriter sw = new StreamWriter(fileName, true))
{
sw.WriteLine("VERSION={0} ISSV=1", version);
sw.Flush();
Stop = false;
while (!Stop)
{
string line = queue.Take();
if (!string.IsNullOrEmpty(line))
{
string eline = Base.LogES.DESEncrypt(line, "AKB48Show!",
(version * version).ToString());
sw.WriteLine(eline);
sw.Flush();
}
}
}
});
}
示例8: Typical
public void Typical ()
{
using (var ms = new MemoryStream ())
using (var sw = new StreamWriter (ms))
{
XDocument doc;
XmlNamespaceManager namespaceManager;
using (var stream = AssemblyExtensions.OpenScopedResourceStream<Program> ("Template.cxml"))
using (var reader = XmlReader.Create (stream))
{
doc = XDocument.Load (reader);
namespaceManager = new XmlNamespaceManager (reader.NameTable);
namespaceManager.AddNamespace ("c", Program.CollectionNamespace.NamespaceName);
}
using (var cw = new CollectionWriter (ms, Program.WriterSettings, futureCw =>
{
futureCw.Flush ();
sw.Write (ProgramTest.ExpectedAnsweredAndAccepted);
sw.Flush ();
})
)
{
doc.Save (cw);
}
sw.Flush ();
ProgramTest.AssertStreamsAreEqual<CollectionWriterTest> ("CollectionWithInjectedItems.cxml", ms);
}
}
示例9: WriteContentToText
/// <summary>
/// 在指定文件中写入指定的内容
/// </summary>
/// <param name="strPathName">需要写入的文本名称</param>
/// <param name="strContent">写入的内容</param>
/// <returns></returns>
public static bool WriteContentToText(string strPathName, string strContent)
{
try
{
if (strPathName == null || strPathName == String.Empty)
return false;
if (!File.Exists(strPathName))
{
File.CreateText(strPathName);
}
FileStream fs = new FileStream(strPathName, FileMode.Open, FileAccess.Write);
StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.GetEncoding("GB2312"));//通过指定字符编码方式可以实现对汉字的支持,否则在用记事本打开查看会出现乱码
sw.Flush();
sw.BaseStream.Seek(0, SeekOrigin.End); //从哪里开始写入.
sw.WriteLine(strContent);
sw.Flush();
sw.Close();
fs.Close();
return true;
}
catch
{
return false;
}
}
示例10: write
public void write(string word)
{
StreamWriter sr;
if (File.Exists(str+"\\load.txt")) //如果文件存在,则创建File.AppendText对象
{
sr = File.AppendText(str+"\\load.txt");
}
else //如果文件不存在,则创建File.CreateText对象
{
sr = File.CreateText(str+"\\load.txt");
}
// sr.WriteLine(str);
sr.Close();
//创建一个文件流,用以写入或者创建一个StreamWriter
FileStream fs = new FileStream(str+"\\load.txt", FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter m_streamWriter = new StreamWriter(fs);
m_streamWriter.Flush();
// 使用StreamWriter来往文件中写入内容
m_streamWriter.BaseStream.Seek(0, SeekOrigin.End);
m_streamWriter.Write(word+"\r\n\r\n\r\n");
//关闭此文件
m_streamWriter.Flush();
m_streamWriter.Close();
}
示例11: EncryptStringForMapServer
public static string EncryptStringForMapServer(string text)
{
string RetVal;
DESCryptoServiceProvider CryptoProvider;
MemoryStream MemoryStream;
CryptoStream CryptoStream;
StreamWriter Writer;
byte[] Bytes;
RetVal = string.Empty;
if (!string.IsNullOrEmpty(text))
{
Bytes = ASCIIEncoding.ASCII.GetBytes(DIMapServer.EncryptionKey);
CryptoProvider = new DESCryptoServiceProvider();
MemoryStream = new MemoryStream(Bytes.Length);
CryptoStream = new CryptoStream(MemoryStream, CryptoProvider.CreateEncryptor(Bytes, Bytes), CryptoStreamMode.Write);
Writer = new StreamWriter(CryptoStream);
Writer.Write(text);
Writer.Flush();
CryptoStream.FlushFinalBlock();
Writer.Flush();
RetVal = Convert.ToBase64String(MemoryStream.GetBuffer(), 0, (int)MemoryStream.Length);
}
return RetVal;
}
示例12: Connect_Server
public static void Connect_Server()
{
//connection setup
ircconnect = new TcpClient(SetupClass.Server, SetupClass.port);
ircstream = ircconnect.GetStream();
PingClass ping = new PingClass();
ping.Start();
reader = new StreamReader(ircstream);
writer = new StreamWriter(ircstream);
writer.WriteLine("PING " + "irc.freenode.net");
writer.Flush();
writer.WriteLine("USER WPChat 8 * : WrongPlanet IRC Client");
writer.Flush();
writer.WriteLine("NICK " + SetupClass.Nick);
writer.Flush();
writer.WriteLine("JOIN " + "#wrongplanet");
writer.Flush();
while (true)
{
//if (reader.ReadLine() != null)
{
System.Messaging.MessageQueue queue = new System.Messaging.MessageQueue(@".\Private$\ServerQueue");
queue.Send(reader.ReadLine());
}
}
}
示例13: GetUploadResponse
public string GetUploadResponse(string url, UploadData upload)
{
string boundary = Guid.NewGuid().ToString().Replace("-", "");
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(url);
request.Method = "POST";
request.UserAgent = "Mozilla/5.0 (Windows NT 6.1; rv:15.0) Gecko/20100101 Firefox/15.0.1";
request.ContentType = "multipart/form-data; boundary=" + boundary;
request.Proxy = null;
MemoryStream PostData = new MemoryStream();
StreamWriter writer = new StreamWriter(PostData);
writer.Write("--" + boundary + "\n");
writer.Write("Content-Disposition: form-data; name=\"{0}\"; filename=\"{1}\"{2}", upload.fieldName, upload.fileName, "\n");
writer.Write(("Content-Type: " + GetContentType(upload.fileName) + "\n") + "\n");
writer.Flush();
writer.Write("\n");
writer.Write("--{0}--{1}", boundary, "\n");
PostData.Write(upload.content, 0, upload.content.Length);
writer.Flush();
request.ContentLength = PostData.Length;
using (Stream s = request.GetRequestStream())
{
PostData.WriteTo(s);
}
PostData.Close();
return new StreamReader(request.GetResponse().GetResponseStream()).ReadToEnd();
}
示例14: Merge
public static void Merge(string targetPath, string[] sourcePaths, Action<string> logMessage)
{
const int bufferSize = 512;
byte[] buffer = new byte[bufferSize];
int bytesRead;
//Use a target stream
using (FileStream ts = new FileStream(targetPath, FileMode.Create, FileAccess.Write, FileShare.None))
using (StreamWriter sw = new StreamWriter(ts))
{
sw.WriteLine("//-- GENERATED BY PxCoco -merge --//");
sw.WriteLine("//-- make sure to modify the source files instead of this one! --//");
foreach (string sourcePath in sourcePaths)
{
if (!File.Exists(sourcePath))
{
Console.WriteLine("Source file " + sourcePath + " does not exist.");
continue;
}
string sourceName = Path.GetFileName(sourcePath);
logMessage.Invoke(String.Format("Adding {0} to {1}.", sourceName, Path.GetFileName(targetPath)));
//Use a source stream
using (FileStream ss = new FileStream(sourcePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
sw.WriteLine("\n#file:" + Path.GetFullPath(sourcePath) + "#");
sw.Flush();
while((bytesRead = ss.Read(buffer, 0, bufferSize)) > 0)
ts.Write(buffer, 0, bytesRead);
}
}
//Switch line processing back to normal, in case the user wants to add stuff here
sw.WriteLine("#file:default#");
sw.Flush();
}
}
示例15: ok_Button_Click
private void ok_Button_Click(object sender, RoutedEventArgs e)
{
if (hotKey1_ComboBox.SelectedIndex < 0 || hotKey2_ComboBox.SelectedIndex<0)
{
MessageBox.Show("信息选择不完全!","提醒",MessageBoxButton.OK,MessageBoxImage.Warning);
return;
}
HotKey.KeyFlags control=HotKey.KeyFlags.MOD_ALT;
int index = 0;
switch (hotKey1_ComboBox.SelectedIndex)
{
case 0: control = HotKey.KeyFlags.MOD_ALT; break;
case 1: control = HotKey.KeyFlags.MOD_CONTROL; index = 1; break;
case 2: control = HotKey.KeyFlags.MOD_SHIFT; index = 2; break;
case 3: control = HotKey.KeyFlags.MOD_WIN; index = 3; break;
}
//撤销先前的热键
HotKeyFactory.UnregisterHotKey();
//注册新的热键
HotKeyFactory.RegisterHotKey(control,(System.Windows.Forms.Keys)hotKey2_ComboBox.SelectedItem);
if (HotKeyFactory.hotKey.IRightRegistered)
{
MessageBox.Show("热键注册成功!");
FileStream fs = new FileStream(HotKeyFactory.path, FileMode.Create, FileAccess.Write);
StreamWriter streamWriter = new StreamWriter(fs);
streamWriter.Flush();
streamWriter.WriteLine(index.ToString()+":"+hotKey2_ComboBox.SelectedItem.ToString());
streamWriter.Flush();
streamWriter.Close();
}
else
MessageBox.Show("热键注册失败!");
}