Cross-process access in. net (C #)
Last Update:2018-12-08
Source: Internet
Author: User
Namespace process_image
{
Public partial class jszg_upload: Form
{
Static bool stop_flag = false;
Public jszg_upload ()
{
InitializeComponent ();
}
Private void upload_button#click (object sender, EventArgs e)
{
Stop_flag = false;
If (this. checkBox1.Checked)
{
String connectionString = "connection String ";
Using (SqlConnection conn = new SqlConnection (connectionString ))
{
Conn. Open ();
SqlCommand cmd = new SqlCommand ("update my_jszg set filemime = null, filebody = null", conn );
Cmd. ExecuteNonQuery ();
Conn. Close ();
}
}
New Thread (uploadImageToDB). Start ();
} // End upload_button#click
Void uploadImageToDB ()
{
// Step 1: Find the files and quantity in the folder
DirectoryInfo myFolder = new DirectoryInfo ("bcd ");
FileInfo [] myFiles = myFolder. GetFiles ();
This. richTextBox1.Text = "found from the folder:" + myFiles. Length. ToString () + "files! "+" \ N ";
This. jindutiao_progressBar1.Maximum = myFiles. Length;
// Step 2: start uploading files
String connectionString = "connection String ";
Using (SqlConnection conn = new SqlConnection (connectionString ))
{
Conn. Open ();
For (int I = 0; I <myFiles. Length; I ++)
{
If (stop_flag)
Break;
// Progress bar
This. jindutiao_progressBar1.Value = I + 1;
This. pictureBox1.ImageLocation = myFiles [I]. FullName;
This. richTextBox1.Text = myFiles [I]. Name + "\ n" + this. richTextBox1.Text;
This. baifenbi_label1.Text = (I + 1) * 1.0)/myFiles. Length) * 100) + "% ";
// Upload the actual data image/jpeg
SqlCommand cmd = new SqlCommand ("update my_jszg set filemime = 'image/jpeg ', filebody = @ myfilebody from my_jszg where ID number = @ myzjhm", conn );
Byte [] fb = new byte [myFiles [I]. Length];
BinaryReader br = new BinaryReader (myFiles [I]. OpenRead ());
Br. Read (fb, 0, (int) myFiles [I]. Length );
Cmd. Parameters. AddWithValue ("@ myfilebody", fb );
Cmd. Parameters. AddWithValue ("@ myzjhm", myFiles [I]. Name. Substring (0, myFiles [I]. Name. LastIndexOf ('.')));
Cmd. ExecuteNonQuery ();
Br. Close ();
} // End
Conn. Close ();
}
MessageBox. Show ("all files have been uploaded! ");
}
// Stop upload
Private void stop_button_Click (object sender, EventArgs e)
{
Stop_flag = true;
}
}
}
In this Code, access to a control is as follows: this. richTextBox1.Text = myFiles [I]. name + "\ n" + this. richTextBox1.Text; only in one thread, If you access the control in two processes, an error will occur! For example, it cannot be accessed in the program's own thread and uploadImageToDB thread.