Tag Archives: csharp
How to allow only one application instance
The following code will ensure that your application can only have one instance active. If the user tries to open the application again while the application is already running then the application will simply quit (in this case after showing a message).
For this to work we will need to modify the Program.cs to check with the use of Mutex if the application is already running or not before we open the main form. Our check will take place in the Main method.
Your code in Program.cs should look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | using System; using System.Reflection; using System.Runtime.InteropServices; using System.Threading; using System.Windows.Forms; namespace WindowsFormsApplication1 { static class Program { [STAThread] static void Main() { /* Retrieve the application Guid attribute. Alternative you can simply use the application name to initialize the Mutex * but it might be risky as other programs might have similar name and make use of the Mutex class as well. */ GuidAttribute appGuid = (GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), true)[0]; // The boolean that will store the value if Mutex was successfully created which will mean that our application is not already running. bool createdNew = true; // Initialize the Mutex object. using (Mutex mutex = new Mutex(true, appGuid.Value, out createdNew)) { /* If Mutex was created successfully which means our application is not running run the application as usual * or else display a message and close the application.*/ if (createdNew) { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1()); } else { MessageBox.Show("Application is already running"); } } } } } |
Feel free to modify the example to suit your needs.
Get value between two strings
You might find this snippet particular useful in cases where you want to get a value between two other values.
This takes advantage of the string’s Split
overload to pass an array of two values. This will result in the string being split twice, once for the first value in the array and once more for the second value. The result will be that the second value in the array that Split
returns is the actual value between the first and the second value we passed as argument.
Code:
1 2 3 4 5 6 7 8 9 10 11 | private string GetBetween(string strSource, string strStart, string strEnd) { string result = string.Empty; if (strSource.Contains(strStart) && strSource.Contains(strEnd)) { result = strSource.Split(new string[] { strStart, strEnd }, StringSplitOptions.None)[1]; } return result; } |
Example:
1 2 3 4 | string source = "this is (my value) a test"; // Returns "(my value)" GetBetween(source, "this is ", " a test"); |
How to get the short path of a directory
In some occasions it might be necessary to use a directory’s short path. This is possible with the use of the Windows GetShortPathName
function.
Implementation:
1 2 3 4 5 6 7 8 9 | [DllImport("kernel32.dll", CharSet = CharSet.Auto)] public static extern uint GetShortPathName(string lpszLongPath, StringBuilder lpszShortPath, uint cchBuffer); private static string GetShortPath(string longPath) { StringBuilder shortPath = new StringBuilder(255); GetShortPathName(longPath, shortPath, 255); return shortPath.ToString(); } |
Simply call the GetShortPath
with the directory you want to get the short path as an argument.
Example:
1 | string applicationShortPath = GetShortPath(Application.ExecutablePath); |
Posted in C#.
Tagged C#, csharp, GetShortPathName, short path, snippet, winforms
Calculate file checksum
You might have noticed by now that a lot of websites list their files checksum values in their downloads section. Checksums are extremely useful when you want to verify that the file you have downloaded from another source is indeed the same file that is hosted on the official website and that it has not been altered in any way.
For this very reason I’ve put together a method that will generate the checksum of the file of your choice. Simply provide the location of the file and the algorithm you wish to compute the checksum with.
1 2 3 4 5 6 7 8 9 10 11 | private string GetFileChecksum(string file, HashAlgorithm algorithm) { string result = string.Empty; using (FileStream fs = File.OpenRead(file)) { result = BitConverter.ToString(algorithm.ComputeHash(fs)).ToLower().Replace("-", ""); } return result; } |
Examples:
1 2 3 4 5 6 7 8 9 10 11 | // a3ccfd0aa0b17fd23aa9fd0d84b86c05 string MD5checksum = GetFileChecksum("c:\\myfile.exe", new MD5CryptoServiceProvider()); // 89c19274ad51b6fbd12fb59908316088c1135307 string SHA1checksum = GetFileChecksum("c:\\myfile.exe", new SHA1CryptoServiceProvider()); // d4ffa4559a1e22167933772d82cf714cd4bb7a0e79511c2424e18bdb619d63a4 string SHA256checksum = GetFileChecksum("c:\\myfile.exe", new SHA256CryptoServiceProvider()); // 3906661b755f22965182f9d1b6f6175cda557c1c66722c60a68037960fc55373586d7db8b24690af212c34ac6df125f08932a24e47ae0f7d6cb2822d8bea4e0f string SHA512checksum = GetFileChecksum("c:\\myfile.exe", new SHA512CryptoServiceProvider()); |
Posted in C#.
Tagged C#, checksum, csharp, HashAlgorithm, snippet, System.Security.Cryptography, winforms
Upload file to FTP
This is a simple method that will allow you to upload a file of your choice to an FTP server.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | private void UploadFtpFile(string filePath, string url) { FileInfo fileInfo = new FileInfo(filePath); FtpWebRequest request = (FtpWebRequest)WebRequest.Create(url); request.Method = WebRequestMethods.Ftp.UploadFile; request.Credentials = new NetworkCredential("ftp username", "ftp password"); request.UseBinary = true; request.ContentLength = fileInfo.Length; using (FileStream fs = fileInfo.OpenRead()) { byte[] buffer = new byte[2048]; int bytesSent = 0; int bytes = 0; using (Stream stream = request.GetRequestStream()) { while (bytesSent < fileInfo.Length) { bytes = fs.Read(buffer, 0, buffer.Length); stream.Write(buffer, 0, bytes); bytesSent += bytes; } } } } |
Keep in mind that you will want to do some error catching to ensure that the file exists, the server is responding and so on.
Simply call the method as follows:
1 | UploadFtpFile("C:\\file_to_upload.jpg", "ftp://example.com/myfolder/name_of_file.jpg"); |