当前位置: 首页>>代码示例>>C#>>正文


C# StreamWriter.Close方法代码示例

本文整理汇总了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();
        }
开发者ID:GeroL,项目名称:MOSA-Project,代码行数:33,代码来源:Execution+Timer.cs

示例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;
		}
	}
开发者ID:Gapti,项目名称:INT-Marks,代码行数:58,代码来源:ItemDataBase.cs

示例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();
        }
    }
开发者ID:JessicaMaxey,项目名称:Networks,代码行数:54,代码来源:EchoServerNoThread.cs

示例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()) ;
        }
    }
开发者ID:ShiJess,项目名称:CompanyStudy,代码行数:51,代码来源:ChatServer.cs

示例5: WriteTextFile

 public static void WriteTextFile(string sFilePathAndName, string sTextContents)
 {
     StreamWriter sw = new StreamWriter(sFilePathAndName);
     sw.WriteLine(sTextContents);
     sw.Flush();
     sw.Close();
 }
开发者ID:TripleLoopGames,项目名称:space-roaches,代码行数:7,代码来源:CommonUtils.cs

示例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);
            }
        }
    }
开发者ID:wuxin0602,项目名称:Nothing,代码行数:34,代码来源:CustomResxImporter.cs

示例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--;
 }
开发者ID:LucasGutierres,项目名称:Oni,代码行数:25,代码来源:SaveMapMPS.cs

示例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();
    }
开发者ID:Raful,项目名称:Hoverboard,代码行数:26,代码来源:HighScore.cs

示例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();
    }
开发者ID:TeeeeeC,项目名称:TelerikAcademy2015-2016,代码行数:25,代码来源:InsertLineNums.cs

示例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");
    }
开发者ID:nehawadhwa,项目名称:ccweb,代码行数:35,代码来源:CP_StartImportText.aspx.cs

示例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();
    }
开发者ID:seenen,项目名称:Tool_AssetBundles,代码行数:27,代码来源:LogFile.cs

示例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();
    }
开发者ID:slop3n,项目名称:TelerikAcademy,代码行数:26,代码来源:DeleteOddLines.cs

示例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;
        }
    }
开发者ID:TerisseNicolas,项目名称:Archip3l,代码行数:30,代码来源:ConstantsLoader.cs

示例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();
        }
    }
开发者ID:JessicaMaxey,项目名称:Networks,代码行数:32,代码来源:EchoServer.cs

示例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;
        }
    }
开发者ID:maronin,项目名称:Project-LimitBreaker,代码行数:31,代码来源:routineManager.cs


注:本文中的StreamWriter.Close方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。