Getting files stored in TextBox1 for conversion

37 Views Asked by At

Good day.

I am newbie in coding and need your help.

I am trying to create an app which will.

  1. Browse all doc, XLS and ppt files through browse button and will show the file names in TextBox1.
  2. When I will click Convert Button, it will grab files from TextBox1 and will convert doc to docs, XLS to XLSX and ppt to PPTX.

I am successful till browsing files and showing all files in TextBox1, but unable to get/select files from TextBox1 for conversion.

What am I looking for?

  1. Get files which are stored in TextBox1 in Convert Button code.
  2. Convert these files to the relevant new format.
  3. Show data in loading bar/ Progress Bar so that I can have an idea how long the conversion takes.

What I tried so far from different forums is shared below

using System;
using System.Collections.Generic;
//using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Runtime.InteropServices;
using Word = Microsoft.Office.Interop.Word;
using Excel = Microsoft.Office.Interop.Excel;
using PowerPoint = Microsoft.Office.Interop.PowerPoint;
using Spire.Doc;
using Spire.Xls;
using Spire.Presentation;
using Microsoft.Office.Interop.Excel;

namespace T_Converter
{
    public partial class Form1 : Form
    {
        private object workbook;

        public object ExcelVersion { get; private set; }

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            BTNClear.Enabled = false;
            BTNConvert.Enabled = false;
        }

        private void BTNBrowse_Click(object sender, EventArgs e)
        {
            var dialog = new OpenFileDialog();
            dialog.InitialDirectory = @"\Desktop";
            dialog.Title = "Browse old office files";
           // dialog.Filter = "Office Files (*.xls)|*.xls";
            dialog.DefaultExt = ".xls";

            
            //OpenFileDialog dialog = new OpenFileDialog();
            dialog.Multiselect = true;
           

            var result = dialog.ShowDialog();

            foreach (string file in dialog.FileNames)
            {
                textBox1.AppendText(Path.GetFileName(file) + Environment.NewLine);
            }

            
            BTNConvert.Enabled = true;
                BTNClear.Enabled = true;

        }

        private void BTNClear_Click(object sender, EventArgs e)
        {
            textBox1.Clear();
            BTNClear.Enabled = false;
            BTNConvert.Enabled = false;
        }

        private void BTNClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void BTNConvert_Click(object sender, EventArgs e)
        {
            
        }
    }

            //Create a Workbook instance
            
            namespace ConvertXlsToXlsx

    {

        class Program

        {

            static void main(string[] args)

            {

                //Create a Workbook instance

                Excel.Workbook workbook = new Excel.Workbook();

                //Load an XLS file

                Workbook.LoadFromFile(@"\Desktop\Test.xlsx");



                //Convert the file to XLSX format

                workbook.SaveToFile(@"C:\Users\Test\Desktop\test.xlsx", ExcelVersion.Version2016);
                MessageBox.Show("OK");
            }

        }

    }

}
    
1

There are 1 best solutions below

0
Aamir Karim On

The following code is here which solve my issue. Replies on this post also helped but complete solution is found from experts in our company.

private void BTNBrowse_Click(object sender, EventArgs e)
    {
        var dialog = new OpenFileDialog();
        dialog.InitialDirectory = @"\Desktop";
        dialog.Title = "Browse old office files";
        dialog.Filter = "Excel Files (*.xls)|*.xls|Word Files(*.doc)|*.doc|PowerPoint Files(*.ppt)|*.ppt";
        dialog.DefaultExt = ".xls";

        dialog.Multiselect = true;

        var result = dialog.ShowDialog();

        foreach (string file in dialog.FileNames)
        {

            textBox1.AppendText(file + Environment.NewLine);
        }
        // Update textbox2 with the total number of selected files in a formatted way
        int totalFiles = dialog.FileNames.Length;
        textBox2.Text = $"{totalFiles:D3}";

        BTNConvert.Enabled = true;
        BTNClear.Enabled = true;

    }

    private void BTNClear_Click(object sender, EventArgs e)
    {
        textBox1.Clear();
        BTNClear.Enabled = false;
        BTNConvert.Enabled = false;
        progressBar1.Value = 0;
        textBox2.Text = "000";
    }

    private void BTNClose_Click(object sender, EventArgs e)
    {
        this.Close();
    }

    private void BTNConvert_Click(object sender, EventArgs e)
    {
        // ProgressBar
        backgroundWorker1.WorkerReportsProgress = true;
        backgroundWorker1.RunWorkerAsync();

        string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
        string outputFolder = Path.Combine(desktopPath, "Converted Files");

        // Loop for multiple files
        for (int i = 0; i < textBox1.Lines.Length; i++)
        {
            string filepath = textBox1.Lines[i].Replace("\r\n", string.Empty);

            string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(filepath);
            string outputFilePath = Path.Combine(outputFolder, fileNameWithoutExtension);

            if (filepath.EndsWith(".xls"))
            {
                Excel.Application excelApp = null;
                Excel.Workbook workbook = null;

                try
                {
                    excelApp = new Excel.Application();
                    workbook = excelApp.Workbooks.Open(filepath);

                    string outputXlsxFilePath = outputFilePath + ".xlsx";

                    workbook.SaveAs(outputXlsxFilePath, Excel.XlFileFormat.xlOpenXMLWorkbook);
                }
                catch (Exception ex)
                {
                    // Handle exceptions
                }
                finally
                {
                    if (workbook != null)
                        Marshal.ReleaseComObject(workbook);

                    if (excelApp != null)
                    {
                        excelApp.Quit();
                        Marshal.ReleaseComObject(excelApp);
                    }
                }
            }
            else if (filepath.EndsWith(".doc"))
            {
                Application wordApp = null;
                Document doc = null;

                try
                {
                    wordApp = new Application();
                    doc = wordApp.Documents.Open(filepath);

                    string outputDocxFilePath = outputFilePath + ".docx";

                    doc.SaveAs2(outputDocxFilePath, WdSaveFormat.wdFormatXMLDocument, CompatibilityMode: WdCompatibilityMode.wdWord2013);
                }
                catch (Exception ex)
                {
                    // Handle exceptions
                }
                finally
                {
                    if (doc != null)
                        doc.Close();

                    if (wordApp != null)
                    {
                        wordApp.Quit();
                        Marshal.ReleaseComObject(wordApp);
                    }
                }
            }
            else if (filepath.EndsWith(".ppt"))
            {
                PowerPoint.Application pptApp = null;
                PowerPoint.Presentation presentation = null;

                try
                {
                    pptApp = new PowerPoint.Application();
                    presentation = pptApp.Presentations.Open(filepath,
                        Microsoft.Office.Core.MsoTriState.msoTrue,
                        Microsoft.Office.Core.MsoTriState.msoFalse,
                        Microsoft.Office.Core.MsoTriState.msoFalse);

                    string outputPptxFilePath = outputFilePath + ".pptx";

                    presentation.SaveAs(outputPptxFilePath, PowerPoint.PpSaveAsFileType.ppSaveAsOpenXMLPresentation, Microsoft.Office.Core.MsoTriState.msoTriStateMixed);
                }
                catch (Exception ex)
                {
                    // Handle exceptions
                }
                finally
                {
                    if (presentation != null)
                        presentation.Close();

                    if (pptApp != null)
                    {
                        pptApp.Quit();
                        Marshal.ReleaseComObject(pptApp);
                    }
                }
            }
        }

        MessageBox.Show("Conversion completed. \nYour converted files are saved in ''Converted Files'' folder created on your desktop.");
    }


    private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
    {
        for (int j = 1; j <= 100; j++)
        {
            // Wait 50 milliseconds.  
            Thread.Sleep(50);
            // Report progress.  
            backgroundWorker1.ReportProgress(j);

        }

    }

    private void backgroundWorker1_ProgressChange(object sender, ProgressChangedEventArgs e)
    {
        // Change the value of the ProgressBar   
        progressBar1.Value = e.ProgressPercentage;
        // Set the text.  
        this.Text = e.ProgressPercentage.ToString();
    }
}

}