本文整理汇总了C#中StreamWriter.Close方法的典型用法代码示例。如果您正苦于以下问题:C# StreamWriter.Close方法的具体用法?C# StreamWriter.Close怎么用?C# StreamWriter.Close使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类StreamWriter
的用法示例。
在下文中一共展示了StreamWriter.Close方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: AppendResultsToFile
public void AppendResultsToFile(String Name, double TotalTime)
{
FileStream file;
file = new FileStream(Name, FileMode.Append, FileAccess.Write);
StreamWriter sw = new StreamWriter(file);
sw.Write("***************************************\n");
sw.Write("Total | No Subs| %Total |%No Subs| Name\n");
foreach (CNamedTimer NamedTimer in m_NamedTimerArray)
{
if (NamedTimer.GetTotalSeconds() > 0)
{
String OutString;
OutString = String.Format("{0:0.0000}", NamedTimer.GetTotalSeconds())
+ " | " + String.Format("{0:0.0000}", NamedTimer.GetTotalSecondsExcludingSubroutines())
+ " | " + String.Format("{0:00.00}", System.Math.Min(99.99, NamedTimer.GetTotalSeconds() / TotalTime * 100)) + "%"
+ " | " + String.Format("{0:00.00}", NamedTimer.GetTotalSecondsExcludingSubroutines() / TotalTime * 100) + "%"
+ " | "
+ NamedTimer.m_Name;
OutString += " (" + NamedTimer.m_Counter.ToString() + ")\n";
sw.Write(OutString);
}
}
sw.Write("\n\n");
sw.Close();
file.Close();
}
示例2: Save
public void Save(string path, ItemType itemType)
{
TextWriter WriteFileStream = new StreamWriter(path);
XmlSerializer serializer;
switch(itemType)
{
case ItemType.Armor:
serializer = new XmlSerializer(typeof(List<Armor>));
serializer.Serialize(WriteFileStream,ArmorList);
WriteFileStream.Close ();
break;
case ItemType.Weapon:
serializer = new XmlSerializer(typeof(List<Weapon>));
serializer.Serialize(WriteFileStream,WeaponList);
WriteFileStream.Close ();
break;
case ItemType.Misc:
serializer = new XmlSerializer(typeof(List<Misc>));
serializer.Serialize(WriteFileStream, MiscList);
WriteFileStream.Close();
break;
case ItemType.Consumable:
serializer = new XmlSerializer(typeof(List<Consumable>));
serializer.Serialize(WriteFileStream, ConsumableList);
WriteFileStream.Close();
break;
case ItemType.Quest:
serializer = new XmlSerializer(typeof(List<Quest>));
serializer.Serialize(WriteFileStream, QuestList);
WriteFileStream.Close();
break;
case ItemType.Enhancer:
serializer = new XmlSerializer(typeof(List<Enhancer>));
serializer.Serialize(WriteFileStream, EnhancerList);
WriteFileStream.Close();
break;
case ItemType.Generator:
serializer = new XmlSerializer(typeof(List<Generator>));
serializer.Serialize(WriteFileStream, GeneratorList);
WriteFileStream.Close();
break;
}
}
示例3: Main
public static void Main(String[] args)
{
StreamReader sr=null;
StreamWriter sw=null;
TcpClient client=null;
TcpListener server=null;
try {
//Echo servers listen on port 7
int portNumber = 7;
//Echo server first binds to port 7
server = new TcpListener(portNumber);
//Server starts listening
server.Start();
//Echo server loops forever, listening for clients
for(;;) {
Console.WriteLine("Waiting for a connection....");
//Accept the pending client connection and return a client
//initialized for communication
//This method will block until a connection is made
client = server.AcceptTcpClient();
Console.WriteLine("Connection accepted.");
//Make a user-friendly StreamReader from the stream
sr=new StreamReader(client.GetStream());
//Make a user-friendly StreamWriter from the stream
sw=new StreamWriter(client.GetStream());
String incoming=sr.ReadLine();
while (incoming!=".") {
Console.WriteLine("Message received: "+incoming);
sw.WriteLine(incoming);
sw.Flush();
Console.WriteLine("Message Sent back: " + incoming);
incoming=sr.ReadLine();
}
Console.WriteLine("Client sent '.': closing connection.");
sr.Close();
sw.Close();
client.Close();
}
} catch (Exception e) {
Console.WriteLine(e+" "+e.StackTrace);
} finally {
if (sr!=null) sr.Close();//check if the stream reader is present - if it is, close it
if (sw!=null) sw.Close();//check if the stream writer is present - if it is, close it
if (client!=null) client.Close();
//Release the port and stop the server
server.Stop();
}
}
示例4: Main
public static void Main()
{
try
{
bool status = true ;
string servermessage = "" ;
string clientmessage = "" ;
TcpListener tcpListener = new TcpListener(8100) ;
tcpListener.Start() ;
Console.WriteLine("Server Started") ;
Socket socketForClient = tcpListener.AcceptSocket() ;
Console.WriteLine("Client Connected") ;
NetworkStream networkStream = new NetworkStream(socketForClient) ;
StreamWriter streamwriter = new StreamWriter(networkStream) ;
StreamReader streamreader = new StreamReader(networkStream) ;
while(status)
{
if(socketForClient.Connected)
{
servermessage = streamreader.ReadLine() ;
Console.WriteLine("Client:"+servermessage) ;
if((servermessage== "bye" ))
{
status = false ;
streamreader.Close() ;
networkStream.Close() ;
streamwriter.Close() ;
return ;
}
Console.Write("Server:") ;
clientmessage = Console.ReadLine() ;
streamwriter.WriteLine(clientmessage) ;
streamwriter.Flush() ;
}
}
streamreader.Close() ;
networkStream.Close() ;
streamwriter.Close() ;
socketForClient.Close() ;
Console.WriteLine("Exiting") ;
}
catch(Exception e)
{
Console.WriteLine(e.ToString()) ;
}
}
示例5: WriteTextFile
public static void WriteTextFile(string sFilePathAndName, string sTextContents)
{
StreamWriter sw = new StreamWriter(sFilePathAndName);
sw.WriteLine(sTextContents);
sw.Flush();
sw.Close();
}
示例6: OnPostprocessAllAssets
public static void OnPostprocessAllAssets(string[] importedAssets, string[] deletedAssets, string[] movedAssets, string[] movedFromAssetPaths)
{
foreach (string asset in importedAssets)
{
if (asset.EndsWith(".resx"))
{
string filePath = asset.Substring(0, asset.Length - Path.GetFileName(asset).Length) + "Generated Assets/";
string newFileName = filePath + Path.GetFileNameWithoutExtension(asset) + ".txt";
if (!Directory.Exists(filePath))
{
Directory.CreateDirectory(filePath);
}
//Delete the file if it already exists
if(File.Exists(newFileName))
{
File.Delete(newFileName);
}
StreamReader reader = new StreamReader(asset);
string fileData = reader.ReadToEnd();
reader.Close();
FileStream resourceFile = new FileStream(newFileName, FileMode.OpenOrCreate, FileAccess.Write);
StreamWriter writer = new StreamWriter(resourceFile);
writer.Write(fileData);
writer.Close();
resourceFile.Close();
AssetDatabase.Refresh(ImportAssetOptions.Default);
}
}
}
示例7: Update
void Update()
{
if(TileSettings.canUseSave == true)
{
grid();
TileSettings.canUseSave = false;
}
if(Input.GetKeyDown (KeyCode.F1) && canSave < 0)
{
grid();
canSave = 150;
using (StreamWriter file = new StreamWriter("MapSettings2.mps"))
{
for(var i = 0;i < linha;i++)
{
for (var n = 0;n < coluna;n++)
{
file.WriteLine("|" + grid_type[i,n]);
}
}
file.Close();
}
}
canSave--;
}
示例8: AddToHighScore
void AddToHighScore(float time)
{
highScoreList.Add(new KeyValuePair<string, float>(userName, time));
highScoreList.Sort((firstPair, nextPair) =>
{
return firstPair.Value.CompareTo(nextPair.Value);
});
//Make sure highScoreList doesn't have too many elements
if (highScoreList.Count > maxScoreCount)
{
//Remove the last element
highScoreList.RemoveAt(highScoreList.Count - 1);
}
StreamWriter file=new StreamWriter(filePath);
//Write the updated high score list to the file
for (int i = 0; i < highScoreList.Count; i++) //Iterate through highScoreList
{
file.WriteLine(highScoreList[i].Key.ToString() + ":" + highScoreList[i].Value.ToString());
}
file.Close();
}
示例9: Main
static void Main()
{
/*
Problem 3. Line numbers
Write a program that reads a text file and inserts line numbers in front of each of its lines.
The result should be written to another text file.
*/
StreamReader reader = new StreamReader("Read.txt");
StreamWriter writer = new StreamWriter("Write.txt");
int countLines = 0;
string line = reader.ReadLine();
using (reader)
{
while (line != null)
{
countLines++;
writer.WriteLine("Line number {0}: {1}", countLines, line);
line = reader.ReadLine();
}
}
writer.Close();
}
示例10: btnImport_Click
protected void btnImport_Click(object sender, EventArgs e)
{
string path = @"C:\Inetpub\wwwroot\File\" + txtFileName.Text;
StreamReader sr = new StreamReader(path);
string strTextToSplit = sr.ReadToEnd();
strTextToSplit = strTextToSplit.Replace("\r", "");
string[] arr = strTextToSplit.Split(new char[] { '\n' });
for (int i = 0; i < arr.GetUpperBound(0); i++)
{
arr[i] = arr[i].Replace("Type=\"Number\"", "Type=\"String\"");
if (arr[i].Substring(0, 13) == "<Row><Cell ss") arr[i] = "";
if (arr[i].Length > 50 && arr[i].Substring(0, 52) == "<Row><Cell><Data ss:Type=\"String\">Lines with Errors:") arr[i] = "";
if (arr[i].IndexOf("This Student has already") != -1) arr[i] = "";
}
path = @"C:\Inetpub\wwwroot\File\" + txtFileName.Text + ".xml";
if (File.Exists(path))
{
File.Delete(path);
}
using (StreamWriter sw = new StreamWriter(path))
{
foreach (string s in arr)
{
sw.WriteLine(s);
}
sw.Close();
}
sr.Close();
Response.Write("DONE");
}
示例11: Write
public void Write(string logfilename, string log, LogType lt)
{
#if UNITY_IPHONE || UNITY_ANDROID
return;
#endif
string filePathName = WriteFile(logfilename);
FileStream fs = new FileStream(filePathName, FileMode.Append);
StreamWriter sw = new StreamWriter(fs);
//开始写入
sw.WriteLine("");
//
string str = "[";
str += System.DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");//默认当天时间。
str += "]";
str += "\t";
str += lt.ToString();
str += "\t";
str += log;
sw.Write(str);
//清空缓冲区
sw.Flush();
//关闭流
sw.Close();
fs.Close();
}
示例12: Main
static void Main(string[] args)
{
string filename = @"..\..\testfile.txt";
StreamReader reader = new StreamReader(filename);
string row = reader.ReadLine();
int count = 0;
List<string> rows = new List<string>();
while (row != null)
{
if (count % 2 == 0)
{
rows.Add(row);
}
row = reader.ReadLine();
count++;
}
reader.Close();
StreamWriter writer = new StreamWriter(filename, false);
for (int i = 0; i < rows.Count; i++)
{
writer.WriteLine(rows[i]);
}
writer.Close();
}
示例13: loadData
private bool loadData()
{
string line = " ";
if (File.Exists(this.path))
{
StreamReader file = new StreamReader(path);
while (((line = file.ReadLine()) != null) && (line.Length > 2))
{
try
{
ConstantsLoader.constantValues.Add((TypeConstant)Enum.Parse(typeof(TypeConstant), line.Split('=')[0]), line.Split('=')[1]);
}
catch (ArgumentException)
{
Debug.Log("An element with this key already exists.");
return false;
}
}
file.Close();
return true;
}
else
{
StreamWriter file = new StreamWriter(path);
file.Close();
return false;
}
}
示例14: Conversation
public void Conversation()
{
try {
Console.WriteLine("Connection accepted.");
//Make a user-friendly StreamReader from the stream
sr=new StreamReader(client.GetStream());
//Make a user-friendly StreamWriter from the stream
sw=new StreamWriter(client.GetStream());
String incoming=sr.ReadLine();
while (incoming!=".") {
Console.WriteLine("Message received: "+incoming);
sw.WriteLine(incoming);
sw.Flush();
Console.WriteLine("Message Sent back: " + incoming);
incoming=sr.ReadLine();
}
Console.WriteLine("Client sent '.': closing connection.");
sr.Close();
sw.Close();
client.Close();
} catch (Exception e) {
Console.WriteLine(e+" "+e.StackTrace);
} finally {
if (sr!=null) sr.Close();
if (sw!=null) sw.Close();
if (client!=null) client.Close();
}
}
示例15: addExerciseToRoutine
public Routine addExerciseToRoutine(int routineID, int exerciseID)
{
using (var context = new Layer2Container())
{
Routine rc = new Routine();
try
{
Routine rtn = context.Routines.Where(x => x.id == routineID).FirstOrDefault();
Exercise exc = context.Exercises.Where(x => x.id == exerciseID).FirstOrDefault();
if (rtn != null && exc != null && containsExercise(routineID, exerciseID) != true)
{
rtn.Exercises.Add(exc);
context.Routines.ApplyCurrentValues(rtn);
context.SaveChanges();
}
rc = rtn;
}
catch (NullReferenceException e)
{
Console.WriteLine(e.Message + Environment.NewLine + e.StackTrace);
// write off the execeptions to my error.log file
StreamWriter wrtr = new StreamWriter(System.Web.HttpContext.Current.ApplicationInstance.Server.MapPath("~/assets/documents/" + @"\" + "error.log"), true);
wrtr.WriteLine(DateTime.Now.ToString() + " | Error: " + e);
wrtr.Close();
}
return rc;
}
}