Click here to Skip to main content
15,881,803 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello.

I have two export buttons. I want to write exceptions for these buttons that will show a message to user that File is in use or opened by another application. Please help me.

C#
private void pDFExportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dataGridView1.RowCount == 0)
            {
                DialogResult result = MessageBox.Show("Table is empty, Export to PDF is impossible", "Export to PDF", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            else
            {                
                //Creating iTextSharp Table from the DataTable data
                PdfPTable pdfTable = new PdfPTable(dataGridView1.ColumnCount);
                pdfTable.DefaultCell.Padding = 3;
                pdfTable.SetWidths(new int[6] { 35, 90, 70, 70, 70, 90 });
                pdfTable.TotalWidth = 425;
                pdfTable.LockedWidth = true;
                pdfTable.HorizontalAlignment = Element.ALIGN_LEFT;
                //pdfTable.DefaultCell.BorderWidth = 1;

                //Adding Header row
                foreach (DataGridViewColumn column in dataGridView1.Columns)
                {
                    PdfPCell cell = new PdfPCell(new Phrase(column.HeaderText));
                    cell.BackgroundColor = new iTextSharp.text.Color(188, 222, 248);
                    cell.FixedHeight = 18;
                    pdfTable.AddCell(cell);
                }

                //Adding DataRow
                foreach (DataGridViewRow row in dataGridView1.Rows)
                {
                    foreach (DataGridViewCell celli in row.Cells)
                    {
                        try
                        {
                            pdfTable.AddCell(celli.Value.ToString());
                        }
                        catch { }
                    }
                }

                SaveFileDialog sfd = new SaveFileDialog();
                sfd.Filter = "PDF File |*.pdf";
                sfd.Title = "PDF kimi saxlamaq";

                if (sfd.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        Document pdfDoc = new Document(PageSize.A4, 85f, 10f, 28f, 20f);
                        PdfWriter wri = PdfWriter.GetInstance(pdfDoc, new FileStream(sfd.FileName, FileMode.Create));
                        pdfDoc.Open();
                        Paragraph paragraph = new Paragraph("Kreditin ödəmə planı", h);
                        paragraph.Alignment = Element.ALIGN_LEFT;
                        pdfDoc.Add(paragraph);
                        pdfDoc.Add(new Paragraph(" "));
                        pdfDoc.Add(pdfTable);
                        pdfDoc.Close();
                        MessageBox.Show("Table has been exported to PDF.", "Export to PDF", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        System.Diagnostics.Process.Start(Path.GetFullPath(sfd.FileName));
                    }
                    catch 
                    {
                        MessageBox.Show("Table not exported to PDF. Because" + " " + Path.GetFullPath(sfd.FileName) + " " + "is in use", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }
        }

        private void excelExportToolStripMenuItem_Click(object sender, EventArgs e)
        {
            if (dataGridView1.RowCount == 0)
            {
                DialogResult result = MessageBox.Show("Table is empty, Export to Excel is impossible", "Export to Excel", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }

            else
            {
                saveFileDialog1.Title = "Save as Excel";
                saveFileDialog1.FileName = "";
                saveFileDialog1.Filter = "Excel Workbook|*.xlsx|Excel (97-2003) Workbook|*.xls";
                if (saveFileDialog1.ShowDialog() == DialogResult.OK)
                {
                    try
                    {
                        //Creae an Excel application instance
                        Excel.Application ExcelApp = new Excel.Application();
                        ExcelApp.Application.Workbooks.Add(Type.Missing);

                        //Change properties of the Workbook
                        ExcelApp.Columns.ColumnWidth = 13;
                        ExcelApp.Columns[1].ColumnWidth = 5;
                        ExcelApp.get_Range("A1", "A1").Font.Size = 18;
                        //ExcelApp.Rows[13, 5].Interior.Color = Excel.XlRgbColor.rgbLightSkyBlue;

                        Excel.Range chartRange;
                        chartRange = ExcelApp.get_Range("A13", "F13");
                        chartRange.Interior.Color = Excel.XlRgbColor.rgbLightSkyBlue;

                        //ExcelApp.Rows[13].Font.Size = 12;
                        ExcelApp.Cells[13, 1].EntireRow.Font.Bold = true;
                        ExcelApp.Cells.HorizontalAlignment = Microsoft.Office.Interop.Excel.XlHAlign.xlHAlignLeft;

                        ExcelApp.Cells[1, "A"] = "Kreditin ödəmə planı";
                        ExcelApp.Cells[2, "A"] = "";
                        ExcelApp.Cells[3, "A"] = "Ödəniş metodu:" + " " + comboBox3.Text;
                        ExcelApp.Cells[4, "A"] = "Kreditin məbləği:" + " " + kreditmeblegi.ToString() + " " + comboBox1.Text;
                        ExcelApp.Cells[5, "A"] = "Faiz dərəcəsi:" + " " + illikfaiz.ToString() + "% illik";
                        ExcelApp.Cells[6, "A"] = "Kreditin müddəti:" + " " + Convert.ToDouble(textBox3.Text) + " " + comboBox2.Text;
                        ExcelApp.Cells[7, "A"] = "Verilmə tarixi:" + " " + dateTimePicker1.Text;
                        ExcelApp.Cells[8, "A"] = "";
                        ExcelApp.Cells[9, "A"] = "Aylıq ödəniş:" + " " + label9.Text;
                        ExcelApp.Cells[10, "A"] = "Cəmi məbləğ:" + " " + umumiodenis.ToString("N2") + " " + comboBox1.Text;
                        ExcelApp.Cells[11, "A"] = "Ödənilən faiz:" + " " + odenilenfaiz.ToString("N2") + " " + comboBox1.Text;

                        // Storing header part in Excel
                        for (int i = 1; i < dataGridView1.Columns.Count + 1; i++)
                        {
                            ExcelApp.Cells[13, i] = dataGridView1.Columns[i - 1].HeaderText;
                        }

                        //Storing each row and column value to excel sheet
                        for (int j = 0; j < dataGridView1.Rows.Count; j++)
                        {
                            for (int k = 0; k < dataGridView1.Columns.Count; k++)
                            {
                                ExcelApp.Cells[j + 14, k + 1] = dataGridView1.Rows[j].Cells[k].Value.ToString();
                            }
                        }

                        ExcelApp.ActiveWorkbook.SaveCopyAs(saveFileDialog1.FileName.ToString());
                        ExcelApp.ActiveWorkbook.Saved = true;
                        ExcelApp.Quit();

                        MessageBox.Show("Table has been exported to Excel.", "Export to Excel", MessageBoxButtons.OK, MessageBoxIcon.Information);
                        System.Diagnostics.Process.Start(Path.GetFullPath(saveFileDialog1.FileName));
                    }
                    catch
                    {
                        MessageBox.Show("Table not exported to PDF. Because" + " " + Path.GetFullPath(saveFileDialog1.FileName) + " " + "is in use.", "Warning", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                    }
                }
            }


What I have tried:

I used catch (IOException) in first button, it worked, but same exception not worked in the second button. Please show me clearly how to write exceptions for these buttons.
Posted

1 solution

You could call this method at the beginning of your method:

C#
public static string IsFileOpen(string filename)
{
    string result = string.Empty;
    try
    {
        if (File.Exists(filename))
        {
            using (FileStream fs = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None))
            {
            }
        }
    }
    catch(Exception ex)
    {
        result = ex.Message;
    }
    return result;
}


like so:

C#
string result = IsFileOpen(myFileName)
if (!string.IsNullOrEmpty(result))
{
    MessageBox.Show(string.Format("Stupid rabbit, Trix are for kids! Because {0}", result));
}
else
{
    ...
    // your existing code goes here
    ...
}
 
Share this answer
 
v2
Comments
Member 12425208 27-Oct-16 9:22am    
Thank you very much for your reply. Since I am beginner in C Sharp, I have some misunderstandings. I did so as you mentioned. But it didn't work. I am sure I did wrong.

public static string IsFileOpen(string filename)
{
string result = string.Empty;
try
{
if (File.Exists(filename))
{
using (FileStream fs = File.Open(filename, FileMode.Open, FileAccess.Read, FileShare.None))
{
}
}
}
catch(Exception ex)
{
result = ex.Message;
}
return result;
}

SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "PDF File |*.pdf";
sfd.Title = "PDF kimi saxlamaq";

if (sfd.ShowDialog() == DialogResult.OK)
{
string result = IsFileOpen(myFileName)
if (!string.IsNullOrEmpty(result))
{
MessageBox.Show(string.Format("Stupid rabbit, Trix are for kids! Because {0}", result));
}
else
{
Document pdfDoc = new Document(PageSize.A4, 85f, 10f, 28f, 20f);
PdfWriter wri = PdfWriter.GetInstance(pdfDoc, new FileStream(sfd.FileName, FileMode.Create));
pdfDoc.Open();
Paragraph paragraph = new Paragraph("Kreditin ödəmə planı", h);
paragraph.Alignment = Element.ALIGN_LEFT;
pdfDoc.Add(paragraph);
pdfDoc.Add(new Paragraph(" "));
pdfDoc.Add(pdfTable);
pdfDoc.Close();
MessageBox.Show("Ödəniş cədvəli PDF-ə çıxarıldı.", "PDF-ə çıxartma", MessageBoxButtons.OK, MessageBoxIcon.Information);
System.Diagnostics.Process.Start(Path.GetFullPath(sfd.FileName));
}
}

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900