C#实现txt定位指定行完整实例
本文实例讲述了C#实现txt定位指定行的方法。分享给大家供大家参考。具体实现方法如下:
usingSystem; usingSystem.Collections.Generic; usingSystem.Linq; usingSystem.Text; usingSystem.Diagnostics; usingSystem.IO; usingSystem.Runtime.InteropServices; namespaceWfpApp { classPositionNotepad { [DllImport("User32.dll",EntryPoint="FindWindow")] privatestaticexternIntPtrFindWindow(stringlpClassName,stringlpWindowName); [DllImport("user32.dll")] staticexternIntPtrFindWindowEx(IntPtrhwndParent,IntPtrhwndChildAfter,stringlpszClass,stringlpszWindow); [DllImport("user32.dll")] staticexternboolSetForegroundWindow(IntPtrhWnd); ///<summary> ///定位到txt文件指定行 ///</summary> ///<paramname="strFullName">文件路径</param> ///<paramname="strRow">指定行</param> ///<returns>定位是否成功</returns> publicstaticboolPositionNotePad(stringstrFullName,stringstrRow) { intiRow; int.TryParse(strRow,outiRow); if(iRow<=0) { returnfalse; } //查看当前文件是否已打开 IntPtrhwnd=FindWindow("Notepad",string.Format("{0}-记事本",Path.GetFileName(strFullName))); if(hwnd.ToInt32()==0) { Processp=Process.Start(@"notepad.exe",strFullName); //等一秒,等文本打开,焦点去到notepad p.WaitForInputIdle(1000); System.Windows.Forms.SendKeys.SendWait("{DOWN"+(iRow-1)+"}"); System.Windows.Forms.SendKeys.SendWait("{HOME}");//行首 System.Windows.Forms.SendKeys.SendWait("+{END}");//选中当前行 returntrue; } else { hwnd=FindWindowEx(hwnd,IntPtr.Zero,"Edit",string.Empty); if(hwnd.ToInt32()==0) returnfalse; else { SetForegroundWindow(hwnd); System.Windows.Forms.SendKeys.SendWait("^{HOME}");//将光标定位到首行 System.Windows.Forms.SendKeys.SendWait("{DOWN"+(iRow-1)+"}"); System.Windows.Forms.SendKeys.SendWait("{HOME}");//行首 System.Windows.Forms.SendKeys.SendWait("+{END}");//选中当前行 } } returntrue; } } }
调用:
stringpath=@"C:\Users\ZKK\Desktop\English.txt"; boolres=PositionNotepad.PositionNotePad(path,"5");
希望本文所述对大家的C#程序设计有所帮助。