C#中的streamwriter和streamreader [英] streamwriter and streamreader in c#

查看:69
本文介绍了C#中的streamwriter和streamreader的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

person operson1 = new person("my name", "my family");
            XmlSerializer xml1 = new XmlSerializer(typeof(person));
            StreamWriter writer1 = new StreamWriter("F:\\test.xml");
            try
            {
                xml1.Serialize(riter1,operson1);
            }
            catch (Exception error)
            {

                System.Console.WriteLine(error.Message);
            }
            finally
            {
                if(writer1!=null){
                    writer1.Close();
                    writer1.Dispose();

                }

必须使用打开 ()处置 ()此代码?

do i have to use open() and dispose() to this code?

如果是,我什么时候必须使用它?

if yes what time i must use it ?

什么

What will help me ?

推荐答案

StreamWriter类没有打开方法.创建完成后,您只需使用其各种Write ...方法,或者在执行操作时将其传递给XmlSerializer.

The StreamWriter class does not have an open method. Once created you just use its various Write... methods or, as you are doing, you can pass it to the XmlSerializer.

StreamWriter实现IDisposable,因此必须在使用后丢弃.您实际上可以调用Close或Dispose,但无需同时执行这两项操作,因为Close实际上只不过是调用Dispose(请参见 文档).

The StreamWriter implements IDisposable therefore must be disposed after use. You can actually call Close or Dispose but don't need to do both because Close actually just calls Dispose anyway (see documentation).

将代码包装在try/finally中很好,但是您也可以使用'using'语句使代码更简洁:

Wrapping your code in a try/finally is fine, but you can also use the 'using' statement to make your code a bit cleaner:

using (StreamWriter writer = new streamWriter("F:\\test.xml"))
{
   // use writer here...
}

在"using"块的末尾,该对象将自动为您处理.

At the end of the 'using' block, the object will be disposed for you automatically.


这篇关于C#中的streamwriter和streamreader的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆