Thursday, 14 June 2018

Read word or doc file without installing office

To Read word file use NPOI.dll. Install from Nuget and add reference into your project. below is the method for that.


 try
                        {
                            XWPFDocument wDoc = new XWPFDocument();
                            using (FileStream fs = new FileStream(fileName, FileMode.Open))
                            {
                                wDoc = new XWPFDocument(fs);
                            }

                            foreach (XWPFParagraph prg in wDoc.Paragraphs)
                            {
                                resumeText = resumeText + prg.Text;
                            }
                            resumeText = resumeText.ToLower();
                        }
                        catch
                        {


                        }

if still word is not supported by this dll means getting error while reading document then write below code.  in that i have used DocumentFormat.OpenXml.dll. add package from Nuget.

 if (String.IsNullOrEmpty(resumeText))
                        {
                            resumeText = ReadWordDocument(fileName);
                        }


 public string ReadWordDocument(string filepath)
    {
        WordprocessingDocument package = null;
        package = WordprocessingDocument.Open(filepath, true);
     
        StringBuilder sb = new StringBuilder();
        OpenXmlElement element = package.MainDocumentPart.Document.Body;
        if (element == null)
        {
            return string.Empty;
        }

        sb.Append(GetPlainText(element));
        return sb.ToString();
    }

  public string GetPlainText(OpenXmlElement element)
    {
        StringBuilder PlainTextInWord = new StringBuilder();
        foreach (OpenXmlElement section in element.Elements())
        {
            switch (section.LocalName)
            {
                // Text
                case "t":
                    PlainTextInWord.Append(section.InnerText);
                    break;

                case "cr":                          // Carriage return
                case "br":                          // Page break
                    PlainTextInWord.Append(Environment.NewLine);
                    break;

                // Tab
                case "tab":
                    PlainTextInWord.Append("\t");
                    break;

                // Paragraph
                case "p":
                    PlainTextInWord.Append(GetPlainText(section));
                    PlainTextInWord.AppendLine(Environment.NewLine);
                    break;

                default:
                    PlainTextInWord.Append(GetPlainText(section));
                    break;
            }
        }

        return PlainTextInWord.ToString();
    }

Get Chrome and internet explorer browser history

Below is the code to get browser history.

Chrome:

  public class HistoryItem
    {
        public string URL { get; set; }

        public string Title { get; set; }

        public DateTime VisitedTime { get; set; }
    }
    List<HistoryItem> allHistoryItems = new List<HistoryItem>();

 public void GetChromeHistory()
    {
        allHistoryItems = new List<HistoryItem>();
        string chromeHistoryFile = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData) + @"\Google\Chrome\User Data\Default\History";
        if (File.Exists(chromeHistoryFile))
        {

            string filePath = System.Web.Hosting.HostingEnvironment.MapPath("/History/");
            string fileid = "History_" + Guid.NewGuid();
            newFilePath = filePath + fileid;
            File.Copy(chromeHistoryFile, newFilePath);
         
            using (SQLiteConnection connection = new SQLiteConnection
                 ("Data Source=" + newFilePath + ";Version=3;New=False;Compress=True;"))
            {

                DataSet dataset = new DataSet();

                SQLiteDataAdapter adapter = new SQLiteDataAdapter
                ("select  * from urls order by last_visit_time desc", connection);
                adapter.Fill(dataset);
                if (dataset != null && dataset.Tables.Count > 0 & dataset.Tables[0] != null)
                {
                    DataTable dt = dataset.Tables[0];


                    foreach (DataRow historyRow in dt.Rows)
                    {
                        HistoryItem historyItem = new HistoryItem
                        {
                            URL = Convert.ToString(historyRow["url"]),
                            Title = Convert.ToString(historyRow["title"])
                        };

                        // Chrome stores time elapsed since Jan 1, 1601 (UTC format) in microseconds
                        long utcMicroSeconds = Convert.ToInt64(historyRow["last_visit_time"]);

                        // Windows file time UTC is in nanoseconds, so multiplying by 10
                        DateTime gmtTime = DateTime.FromFileTimeUtc(10 * utcMicroSeconds);

                        // Converting to local time
                        DateTime localTime = TimeZoneInfo.ConvertTimeFromUtc(gmtTime, TimeZoneInfo.Local);
                        historyItem.VisitedTime = localTime;

                        allHistoryItems.Add(historyItem);
                    }
                }
            }
        }


        gridChrome.DataSource = allHistoryItems;
        gridChrome.DataBind();
        try
        {
            if (File.Exists(newFilePath))
            {
                File.Delete(newFilePath);
            }
        }
        catch
        {
        }
    }


Internet Explorer:

 public void GetInternetExplorerHistory()
    {

        allHistoryItems = new List<HistoryItem>();

        // Initiate main object
        UrlHistoryWrapperClass urlhistory = new UrlHistoryWrapperClass();


        // Enumerate URLs in History
        UrlHistoryWrapperClass.STATURLEnumerator enumerator =

                                           urlhistory.GetEnumerator();

        // Iterate through the enumeration
        while (enumerator.MoveNext())
        {
            // Obtain URL and Title

            string url = enumerator.Current.URL.Replace('\'', ' ');
            if (url.StartsWith("http"))
            {
                // In the title, eliminate single quotes to avoid confusion
                string title = string.IsNullOrEmpty(enumerator.Current.Title) ? "" : enumerator.Current.Title.Replace('\'', ' ');

                // Create new entry
                HistoryItem historyItem = new HistoryItem
                {
                    URL = url,
                    Title = title
                };
                // Add entry to list
                allHistoryItems.Add(historyItem);
            }
        }

        // Optional
        enumerator.Reset();

        // Clear URL History
        // urlhistory.ClearHistory();

        gridIE.DataSource = allHistoryItems;
        gridIE.DataBind();

    }