发布资源

时间:2016-03-22 11:57:40

标签: c# winforms openfiledialog

我在win form中遇到OpenFileDialog这个问题..

private void btnAllegato_Click(object sender, EventArgs e)
    {

        try
        {

            using (OpenFileDialog openFileDialog1 = new OpenFileDialog())
            {
                string path = string.Empty;

                openFileDialog1.Title = "Seleziona richiestaIT (PDF)..";
                openFileDialog1.Filter = ("PDF (.pdf)|*.pdf");
                openFileDialog1.FilterIndex = 1;
                openFileDialog1.FileName = "";


                if (openFileDialog1.ShowDialog() == DialogResult.OK)
                {

                    //salva l'intero path
                    path = openFileDialog1.FileName;

                    //nome file + estensione
                    string temp = openFileDialog1.SafeFileName;

                    //elimina l'estensione del file con IgnoreCase -> case Unsensitive
                    temp = Regex.Replace(temp, ".pdf", " ", RegexOptions.IgnoreCase);

                    //datatime + replace
                    string timenow = System.DateTime.Now.ToString();

                    //replace data da gg//mm/aaaa  ss:mm:hh  ----->  ad   gg-mm-aaaa_ss-mm-hh  
                    timenow = timenow.Replace(":", "-").Replace("/", "-");//.Replace(" ", " ");     

                    //effettua una copia dal path origine alla cartella nel NAS
                    _url = @"\\192.168.5.7\dati\SGI\GESTIONE IT\RichiesteIT\" + temp + timenow + ".pdf";

                    this.Cursor = Cursors.WaitCursor;

                    System.IO.File.Copy(path, _url);


                    this.Cursor = Cursors.Default;
                }


            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

刚开始......一切都好...... 但是第二次点击btn ...进程循环... OpenFileDialog是开放但是总白... enter image description here

我认为这是处置资源的问题..但我不知道如何解决它。

... ... @EDIT

经过多次尝试后......我意识到问题出现在我完成了 Inserisci>> 之后。 第一次运行良好但是当我点击第二次... btnAllegato 在btnInserisci之后我有循环过程。

enter image description here 代码btnInserisci:

        private void btnInserisci_Click(object sender, EventArgs e)
    {
        try
        {
            if ((_IDRichiedente != -1) && (_data != string.Empty) && (_url != string.Empty))
            {
                //messageBox
                MessageBox.Show(_url);
                QueryAssist qa = new QueryAssist();
                string query = "INSERT INTO RICHIESTA_IT(ID_Risorsa, descrizione_richiesta, modulo_pdf, data_richiesta) VALUES('" + _IDRichiedente + "', '" + txtBreveDescrizione.Text + "', '" + _url + "', '" + _data + "');";
                MessageBox.Show(query);

                qa.runQuery(query);
                // qa.runQuery("INSERT INTO RICHIESTA_IT (ID_Risorsa, data_richiesta) VALUES ('" + _IDRichiedente + "','" + _data + "');");
            }
            else
            {
                MessageBox.Show("Selezionare il richiedente,data o allegato!");
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }

    }

其中private int _IDRichiedente = -1; private string _data = String.Empty; private string _url = string.Empty;是一个类的字段。

QueryAssist是我的个人类,它创建连接,运行查询并断开连接。 代码:

    class QueryAssist
{
    System.Data.OleDb.OleDbConnection _OleDBconnection;

    public QueryAssist()
    {
        this._OleDBconnection = null;
    }

    //riferimento di connessione al db
    private bool connectionDB()
    {
        string connection = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=\"\\\\192.168.5.7\\dati\\Scambio\\Sviluppo\\Impostazioni temporanea db Censimento\\CensimentoIT.accdb\"";
        try
        {
            _OleDBconnection = new System.Data.OleDb.OleDbConnection(connection);
            _OleDBconnection.Open();
            return true;

        }
        catch(Exception ex)
        {
            System.Windows.Forms.MessageBox.Show(ex.Message);
            return false;
        }
    }

    private void disconnectDB()
    {
        try
        {
            _OleDBconnection.Close();
        }
        catch (Exception ex)
        {
            System.Windows.Forms.MessageBox.Show(ex.Message);

        }
    }

    public System.Data.DataTable runQuery(string query)
    {
        try
        {
            if (connectionDB())
            {
                System.Data.DataTable dataTable = new System.Data.DataTable();
                System.Data.OleDb.OleDbCommand sqlQuery = new System.Data.OleDb.OleDbCommand(query, _OleDBconnection);
                System.Data.OleDb.OleDbDataAdapter adapter = new OleDbDataAdapter(sqlQuery);
                adapter.Fill(dataTable);
                disconnectDB();
                return dataTable;
            }
        }
        catch(Exception ex)
        {
            System.Windows.Forms.MessageBox.Show(ex.Message);
        }
        return null;

    }

    public int countRowsQueryResult(string query)
    {
        try
        {
            if (connectionDB())
            {
                System.Data.DataTable dataTable = new System.Data.DataTable();
                System.Data.OleDb.OleDbCommand sqlQuery = new System.Data.OleDb.OleDbCommand(query, _OleDBconnection);
                System.Data.OleDb.OleDbDataAdapter adapter = new OleDbDataAdapter(sqlQuery);
                adapter.Fill(dataTable);
                disconnectDB();
                return dataTable.Rows.Count;
            }
        }
        catch (Exception ex)
        {
            System.Windows.Forms.MessageBox.Show(ex.Message);
        }
        return -1;

    }
}

}

抱歉我的英文

4 个答案:

答案 0 :(得分:0)

我认为File.Copy可能会挂起。尝试使用本地文件路径使用相同的代码,例如" c:\ filename.pdf"作为URL。

//Crea il nome del file di destinazione
string _url = string.Format(@"c:\{0}{1}.pdf", temp, timenow);

如果这种方式正常,则问题在于与NAS的连接。

答案 1 :(得分:0)

当您的应用程序不使用单线程单元公寓COM模型时,通常会发现此问题。

通常,对于WinForms,在Main中的Program.cs方法中,您需要具有[STAThread]属性,例如:

[STAThread]
static void Main()
...

如果您没有,并且您确定不需要MTA,则可以将其添加到那里。

否则,我有这个实用程序代码(我确定我没有写,我只是从某个地方复制它但不能真正给予赞誉,它已经在我的“winforms实用程序类”中一段时间​​了)常见对话框,使用STA创建一个新线程并在那里调用对话框:

public class DialogInvoker
{
   public CommonDialog InvokeDialog;
   private Thread InvokeThread;
   private DialogResult InvokeResult;

   public DialogInvoker(CommonDialog dialog)
   {
      InvokeDialog = dialog;
      InvokeThread = new Thread(new ThreadStart(InvokeMethod));
      InvokeThread.SetApartmentState(ApartmentState.STA);
      InvokeResult = DialogResult.None;
   }

   public DialogResult Invoke()
   {
      InvokeThread.Start();
      InvokeThread.Join();
      return InvokeResult;
   }

   private void InvokeMethod()
   {
      InvokeResult = InvokeDialog.ShowDialog();
   }
}

要使用它,请更改:

if (openFileDialog1.ShowDialog() == DialogResult.OK) 

有关:

if ((new DialogInvoker(openFileDialog1)).Invoke() == DialogResult.OK) 

答案 2 :(得分:-1)

将其从'使用'声明。变化

using (OpenFileDialog openFileDialog1 = new OpenFileDialog())

OpenFileDialog openFileDialog1 = new OpenFileDialog();

看看这是否有所作为。如果是这样,问题在于处理声明。

答案 3 :(得分:-1)

Io suggerirei diprovarecosì:使用非si utilizza con le对话框

try
{

    OpenFileDialog openFileDialog1 = new OpenFileDialog();
    string path = string.Empty;

    openFileDialog1.Title = "Seleziona richiestaIT (PDF)..";
    openFileDialog1.Filter = ("PDF (.pdf)|*.pdf");
    openFileDialog1.FilterIndex = 1;
    openFileDialog1.FileName = "";


    if (openFileDialog1.ShowDialog() == DialogResult.OK)
    {

        //salva l'intero path
        path = openFileDialog1.FileName;

        //Togli l'estensione dal file
        string temp = Path.GetFileNameWithoutExtension(openFileDialog1.FileName);

        //Crea un nome univoco usando data e ora
        string timenow = System.DateTime.Now.ToString("dd-MM-yyyy_ss-mm-hh");


        //Crea il nome del file di destinazione
        string _url = string.Format(@"\\192.168.5.7\dati\SGI\GESTIONE IT\RichiesteIT\{0}{1}.pdf", temp, timenow);

        this.Cursor = Cursors.WaitCursor;

        File.Copy(path, _url);


        this.Cursor = Cursors.Default;
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message);
}