zoukankan      html  css  js  c++  java
  • WPF 打开txt文件

    实现效果

    关键代码

    [DllImport("kernel32.dll")]
    public static extern IntPtr _lopen(string lpPathName, int iReadWrite);
    [DllImport("kernel32.dll")]
    public static extern bool CloseHandle(IntPtr hObject);
    
    public const int OF_READWRITE = 2;
    public const int OF_SHARE_DENY_NONE = 0x40;
    public readonly IntPtr HFILE_ERROR = new IntPtr(-1);
    
    
    //引入System.Windows.Forms.dll
    System.Windows.Forms.OpenFileDialog ofd = new System.Windows.Forms.OpenFileDialog();
    ofd.Multiselect = false;
    ofd.Filter = "txt文件|*.txt";
    
    if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
    	try
    	{
    		if (!File.Exists(ofd.FileName))
    		{
    			MessageBox.Show("文件不存在!");
    			return;
    		}
    
    		IntPtr vHandle = _lopen(ofd.FileName, OF_READWRITE | OF_SHARE_DENY_NONE);
    
    		if (vHandle == HFILE_ERROR)
    		{
    			MessageBox.Show("文件被占用!");
    			CloseHandle(vHandle);
    			return;
    		}
    
    		CloseHandle(vHandle);
    
    		var filePath = ofd.FileName;
    		using (FileStream stream = File.OpenRead(filePath))
    		{
    			TextRange documentTextRange = new TextRange(loadTxtRichTextBox.Document.ContentStart, loadTxtRichTextBox.Document.ContentEnd);
    			string dataFormat = DataFormats.Text;
    			StreamReader sr = new StreamReader(stream, Encoding.Default);
    			documentTextRange.Load(new MemoryStream(Encoding.UTF8.GetBytes(sr.ReadToEnd())), dataFormat);
    
    		}
    	}
    	catch(Exception ex)
    	{
    		MessageBox.Show("出现异常", $"{ex.Message}");
    		return;
    	}
    
    	
    }
    

    示例代码

    OpenTxtFileWindow

    参考资料

    WPF富文本RichTextBox用法

  • 相关阅读:
    linux的crash之hardlock排查记录
    linux 巨页使用测试
    linux 巨页使用测试以及勘误1
    python判断两个list包含关系
    JavaScript--数据结构之栈
    JavaScript--数据结构与算法之列表
    js数组详解:
    基于jQuery的插件开发
    函数的理解:
    JS面向对象:
  • 原文地址:https://www.cnblogs.com/Lulus/p/12547978.html
Copyright © 2011-2022 走看看