lunedì 25 giugno 2012

Importare un file txt, rtf, doc, in un campo testo di una form.

In un oggetto di tipo textBox (denominato qui per esempio "txtScript") di una form possiamo importare del testo tramite c#.
Nell' esempio l'import è per un file di tipo txt, rtf oppure un documento Word.
private void ImportScript()
{
    try
    {
    string pathFile = "";
    string extensionFile;

    //Apertura finestra e scelta del file
    OpenFileDialog dlgOpen = new OpenFileDialog();

    dlgOpen.Title = "Import text";
    dlgOpen.DefaultExt = ".txt";
    dlgOpen.Filter = "Text file (*.txt;*.rtf;*.doc)|*.txt;*.rtf;*.doc";
    dlgOpen.ShowReadOnly = true;
    dlgOpen.InitialDirectory = pathSPS + "Projects";
    dlgOpen.Multiselect = false;

    if (dlgOpen.ShowDialog() == DialogResult.OK)
    {
        pathFile = dlgOpen.FileName;
        extensionFile = dlgOpen.SafeFileName.Substring(
dlgOpen.SafeFileName.Length - 4, 4);
    }
    else
        return;

    //documento con estensione .doc
    if (extensionFile.ToLower().Equals(".doc"))
    {
        {
            Word.ApplicationClass wordApp = new ApplicationClass();
            object file = pathFile;

            object nullobj = System.Reflection.Missing.Value;

            Word.Document docWord = wordApp.Documents.Open(

              ref file, ref nullobj, ref nullobj, ref nullobj,
              ref nullobj, ref nullobj, ref nullobj,
              ref nullobj, ref nullobj, ref nullobj,
              ref nullobj, ref nullobj, ref nullobj,
              ref nullobj, ref nullobj, ref nullobj);

            docWord.ActiveWindow.Selection.WholeStory();

            docWord.ActiveWindow.Selection.Copy();

            IDataObject data = Clipboard.GetDataObject();

            this.txtScript.Text = data.GetData(DataFormats.Text).ToString();

            docWord.Close(ref nullobj, ref nullobj, ref nullobj);
        }
    }
    //documento con estensione .txt
    else if (extensionFile.ToLower().Equals(".txt"))
    {
        using (System.IO.StreamReader sr =
 new System.IO.StreamReader(pathFile))
        {
            this.txtScript.Text = sr.ReadToEnd();
        }
    }
    //documento con estensione .rtf
    else if (extensionFile.ToLower().Equals(".rtf"))
    {
        using (System.IO.StreamReader sr =
 new System.IO.StreamReader(pathFile))
        {
            this.txtScript.Rtf = sr.ReadToEnd(); // di tipo Rtf!
        }
    }
    }
    catch (Exception ex)
    {
        log.Error(ex);
    }
}