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

  • 相关阅读:
    让我自闭了两个星期的题 Hello xtCpc
    kmp 回忆训练2 poj3461
    kmp 字符串匹配
    线段树之动态开点  HDU 6183 Color it.
    两个思维
    codeforces 300E Empire Strikes Back
    codeforces1392 E Omkar and Duck
    codeforces1169D
    HDU4335 欧拉函数及降幂
    HDU2588GCD(欧拉函数)
  • 原文地址:https://www.cnblogs.com/Lulus/p/12547978.html
Copyright © 2011-2022 走看看