新的空间

  博客园 :: 首页 :: 新随笔 :: 联系 :: 订阅 :: 管理 ::

读写文件示例代码

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace study
{
    
public partial class Form3 : Form
    
{
        
public Form3()
        
{
            InitializeComponent();
        }


        
private void button1_Click(object sender, EventArgs e)
        
{
            String editingFileName 
= "";
            Boolean saveAllowed 
= true;

            
// Displays the OpenFileDialog.
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            
{
                
// Opens the file stream for the file selected by the user.
                using (System.IO.Stream userStream = openFileDialog1.OpenFile())
                
{
                    
this.RtfBoxMain.LoadFile(userStream,
                        RichTextBoxStreamType.PlainText);
                    userStream.Close();
                }


                
// Tries to get the file name selected by the user.
                
// Failure means that the application does not have
                
// unrestricted permission to the file.
                try
                
{
                    editingFileName 
= openFileDialog1.FileName;
                }

                
catch (Exception ex)
                
{
                    
if (ex is System.Security.SecurityException)
                    
{
                        
// The application does not have unrestricted permission 
                        
// to the file so the save feature will be disabled.
                        saveAllowed = false;
                    }

                    
else
                    
{
                        
throw ex;
                    }

                }

            }


        }


        
private void button2_Click(object sender, EventArgs e)
        
{
            String editingFileName 
= "";
            Boolean saveAllowed 
= true;

            
// Displays the OpenFileDialog.
            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            
{
                
// Opens the file stream for the file selected by the user.
                using (System.IO.Stream userStream = saveFileDialog1.OpenFile())
                
{
                    
this.RtfBoxMain.SaveFile(userStream,
                        RichTextBoxStreamType.PlainText);
                    userStream.Close();
                }

            }

        }

    }

}
posted on 2006-06-17 19:41  旭萌  阅读(186)  评论(0)    收藏  举报