Useful C # FAQ

Source: Internet
Author: User

Q: How to add some nodes to a node location in the XMl document, instead of writing the entire file?
A: XmlDocument xmldoc = new XmlDocument ();
XmlDoc. Load (filePath );
 
XmlNode root = xmlDoc. DocumentElement. SelectSingleNode (xPath );
 
XmlNode newElem = xmlDoc. CreateNode (XmlNodeType. Element, "pages ","");
 
Root. AppendChild (newElem );
 
XmlDoc. Save (filePath );
---------------------------------------------------------------
 
 
TextWriter tw = new StreamWriter (@ "C: \ csharp \ 06 \ iverson. xml ");
XmlTextWriter writer = new XmlTextWriter (tw );
Writer. WriteStartElement ("Human ");
Writer. WriteComment ("this is test sample ");
Writer. WriteStartElement ("Name ");
Writer. WriteString ("Iverson ");
Writer. WriteEndElement ();
Writer. WriteElementString ("tel", "13020024783 ");
Writer. WriteStartElement ("Jobs ");
Writer. WriteStartAttribute ("Job1", null );
Writer. WriteString ("Author ");
Writer. WriteEndAttribute ();
Writer. WriteStartAttribute ("Job2", null );
Writer. WriteString ("Teacher ");
Writer. WriteEndAttribute ();
Writer. WriteEndElement ();
Writer. WriteEndElement ();
Writer. Close ();

Q: c # How to execute an external exe file when developing winform?
Like the vb shell!

A: simple execution is relatively simple:
Process myProcess = new Process ();
ProcessStartInfo myProcessStartInfo = new ProcessStartInfo ();
MyProcessStartInfo. FileName = "Netpad ";
MyProcess. StartInfo = myProcessStartInfo;
MyProcess. Start ();
 
But my problem is quite troublesome.
---------------------------------------------------------------
 
Using System. Diagnostics;
Process. Start ("external exe file ");
 
For example:
Try
{
Process. Start ("regedit"); // Start the Registry Editor.
}
Catch
{
MessageBox. Show ("program startup error ");
}
---------------------------------------------------------------
 
Process. Start ("external exe file ");
Just open a process.

Q: How can I implement data exchange between two programs?
A: Method 1:
Through the database
Method 2:
Configuration File
For webform: You can use Session
 
Wish u good luck
Greatsft
---------------------------------------------------------------
 
Two Methods: write data to a file and read data from another program!
The second method is to use socket to define a channel and communicate with each other. It is like network communication, but it is actually on the same computer! The premise is to have a TCP/IP environment! It is also suitable for high requirements on data timeliness.
The above two methods are relatively simple, I thought.
It is best to see if it is possible to use the global Dll call Method for sharing between processes! However, I do not have any experience in this field!
---------------------------------------------------------------
 
 
If the two programs only communicate with each other, you can use the following methods:
 
1. share files or databases
 
2. Pipeline
 
3. Mail Trough
 
4. Use Socket
 
5. Others
 
If the two programs are not only data communication, but also communication processing (that is, program A can call the method of program B), you can use the following methods:
 
1. Dcom
 
2.. net Remoting
 
3. Web Service
---------------------------------------------------------------
 
Several methods for communication between processes:
 
In Windows, processes often need to exchange data for data communication. Common methods include:
 
Use memory ing files
Share memory through DLL
Use SendMessage to send the WM_COPYDATA message to another process.
 
Compared with the previous two complex implementations, WM_COPYDATA is undoubtedly a cost-effective method.
 
The main purpose of a WM_COPYDATA message is to allow the transfer of read-only data between processes. During WM_COPYDATA message transmission, Windows does not provide the inheritance synchronization mode. We recommend that you use the SendMessage function in the SDK documentation. The receiver does not return the message before the data copy is completed, so that the sender cannot delete or modify the data:
 
The prototype of this function and the structure to be used are as follows:
 
SendMessage (hwnd, WM_COPYDATA, wParam, lParam );
The hexadecimal number of WM_COPYDATA is 0x004A.
 
WParam is set to the handle of the window containing data. LParam points to a COPYDATASTRUCT structure:
Typedef struct tagCOPYDATASTRUCT {
DWORD dwData; // user-defined data
DWORD cbData; // data size
PVOID lpData; // pointer to data
} COPYDATASTRUCT;
This structure is used to define user data.
 
The specific process is as follows:
 
 
First, find the receiver's handle using FindWindow on the sender, and then send the WM_COPYDATA message to the receiver.
 
The receiver processes the message in the DefWndProc event. Because the Chinese encoding is two bytes, the length of the byte must be clear when the Chinese character is passed.
 
The body code is as follows:
//---------------------------------------------------
// Sender:
Using System;
Using System. Drawing;
Using System. Collections;
Using System. ComponentModel;
Using System. Windows. Forms;
Using System. Data;
Using System. Runtime. InteropServices;
 
Namespace WinFormSendMsg
{
Public class Form1: System. Windows. Forms. Form
{
Private System. Windows. Forms. TextBox textBox1;
Private System. Windows. Forms. Button button1;
Private System. ComponentModel. Container components = null;
Const int WM_COPYDATA = 0x004A;
Public Form1 ()
{
InitializeComponent ();
}
 
Protected override void Dispose (bool disposing)
{
If (disposing)
{
If (components! = Null)
{
Components. Dispose ();
}
}
Base. Dispose (disposing );
}
 
 
Private void InitializeComponent ()
{
This. textBox1 = new System. Windows. Forms. TextBox ();
This. button1 = new System. Windows. Forms. Button ();
This. SuspendLayout ();
//
// TextBox1
//
This. textBox1.Location = new System. Drawing. Point (184, 24 );
This. textBox1.Name = "textBox1 ";
This. textBox1.Size = new System. Drawing. Size (128, 21 );
This. textBox1.TabIndex = 0;
This. textBox1.Text = "textBox1 ";
//
// Button1
//
This. button1.Location = new System. Drawing. Point (344, 16 );
This. button1.Name = "button1 ";
This. button1.Size = new System. Drawing. Size (112, 32 );
This. button1.TabIndex = 1;
This. button1.Text = "button1 ";
This. button1.Click + = new System. EventHandler (this. button#click );
//
// Form1
//
This. AutoScaleBaseSize = new System. Drawing. Size (6, 14 );
This. ClientSize = new System. Drawing. Size (536,142 );
This. Controls. AddRange (new System. Windows. Forms. Control [] {
This. button1,
This. textBox1 });
This. Name = "Form1 ";
This. Text = "sender form ";
This. ResumeLayout (false );
 
}
 
Static void Main ()
{
Application. Run (new Form1 ());
}
 
[DllImport ("User32.dll", EntryPoint = "SendMessage")]
Private static extern int SendMessage (
Int hWnd, // handle to destination window
Int Msg, // message
Int wParam, // first message parameter
Ref COPYDATASTRUCT lParam // second message parameter
);
 
 
[DllImport ("User32.dll", EntryPoint = "FindWindow")]
Private static extern int FindWindow (string lpClassName, string
LpWindowName );
 
 
Private void button#click (object sender, System. EventArgs e)
{
Int WINDOW_HANDLER = FindWindow (null, @ "receiver form ");
If (WINDOW_HANDLER = 0)
{
 
}
Else
{
Byte [] sarr = System. Text. Encoding. Default. GetBytes (this. textBox1.Text );
Int len = sarr. Length;
 
COPYDATASTRUCT cds;
Cds. dwData = (IntPtr) 100;
Cds. lpData = this. textBox1.Text;
Cds. cbData = len + 1;
SendMessage (WINDOW_HANDLER, WM_COPYDATA, 0, ref cds );
 
 
}
 
}
}
Public struct COPYDATASTRUCT
{
Public IntPtr dwData;
Public int cbData;
[Financialas (UnmanagedType. LPStr)] public string lpData;
}
 
 
}
 
 
//---------------------------------------------------
// Receiver
//---------------------------------------------------
Using System;
Using System. Drawing;
Using System. Collections;
Using System. ComponentModel;
Using System. Windows. Forms;
Using System. Data;
Using System. Runtime. InteropServices;
 
Namespace WindowsFormGetMsg
{
Public class Form1: System. Windows. Forms. Form
{
Private System. Windows. Forms. TextBox textBox1;
Private System. ComponentModel. Container components = null;
Const int WM_COPYDATA = 0x004A;
 
Public Form1 ()
{
InitializeComponent ();
}
 
Protected override void Dispose (bool disposing)
{
If (disposing)
{
If (components! = Null)
{
Components. Dispose ();
}
}
Base. Dispose (disposing );
}
Private void InitializeComponent ()
{
This. textBox1 = new System. Windows. Forms. TextBox ();
This. SuspendLayout ();
//
// TextBox1
//
This. textBox1.Location = new System. Drawing. Point (176, 32 );
This. textBox1.Name = "textBox1 ";
This. textBox1.Size = new System. Drawing. Size (160, 21 );
This. textBox1.TabIndex = 0;
This. textBox1.Text = "textBox1 ";
//
// Form1
//
This. AutoScaleBaseSize = new System. Drawing. Size (6, 14 );
This. ClientSize = new System. Drawing. Size (432,266 );
This. Controls. AddRange (new System. Windows. Forms. Control [] {
This. textBox1 });
This. Name = "Form1 ";
This. Text = "receiver form ";
This. ResumeLayout (false );
 
}
Static void Main ()
{
Application. Run (new Form1 ());
}
 
Protected override void DefWndProc (ref System. Windows. Forms. Message m)
{
Switch (m. Msg)
{
Case WM_COPYDATA:
COPYDATASTRUCT mystr = new COPYDATASTRUCT ();
Type mytype = mystr. GetType ();
Mystr = (COPYDATASTRUCT) m. GetLParam (mytype );
This. textBox1.Text = mystr. lpData;
Break;
Default:
Base. DefWndProc (ref m );
Break;
 
}
 
}
 
}
 
Public struct COPYDATASTRUCT
{
Public IntPtr dwData;
Public int cbData;
[Financialas (UnmanagedType. LPStr)] public string lpData;
}
}

Converts a binary array to an image file.
Convert to a binary array
Public static byte [] GetFileBytes (string Filename)
{
If (Filename = "")
Return null;

FileStream fileStream = new FileStream (Filename, FileMode. Open, FileAccess. Read );
BinaryReader binaryReader = new BinaryReader (fileStream );

Byte [] fileBytes = binaryReader. ReadBytes (int) fileStream. Length );
BinaryReader. Close ();
FileStream. Close ();

Return fileBytes;
}

Convert a binary array to a file
FileStream fileStream = new FileStream ("file path", FileMode. OpenOrCreate, FileAccess. Write );
BinaryWriter binaryWriter = new BinaryWriter (fileStream );

BinaryWriter. Write (fileBytes );
BinaryWriter. Flush ();
BinaryWriter. Close ();
FileStream. Close ();

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.