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用法

  • 相关阅读:
    mongoDB常用命令
    Linux下安装MongoDB
    Linux下mysq基础命令(二)
    Linux下mysql基础命令(一)
    Linux 下使用yum 命令安装MySQL
    Linux 常用命令
    windows7用WMware安装Linux虚拟机详细步骤
    接口测试全流程扫盲
    Jmeter时间格式化
    Jmeter之测试报告
  • 原文地址:https://www.cnblogs.com/Lulus/p/12547978.html
Copyright © 2011-2022 走看看