Snippet: Learning C#

How to Take screenshot and upload to remote server using C#/.Net 4.5 and PHP.

.NET 4.5 includes an HTTP library that makes it incredibly easy to send HTTP GET/POST requests. There is no longer a need to use CURL.
Here is an example utility that uses System.Net.Http to send an image of the screen to a remote server.

private void grabScreen()
        {
            this.mtxUploadLock.WaitOne( /* 10000 */);
            try
            {
                int screenWidth = Screen.PrimaryScreen.Bounds.Width;
                int screenHeight = Screen.PrimaryScreen.Bounds.Height;

                Bitmap screenShot = new Bitmap(
                   screenWidth, screenHeight,
                   System.Drawing.Imaging.PixelFormat.Format32bppArgb
                  );

                Graphics gfx = Graphics.FromImage(screenShot);

                gfx.CopyFromScreen(
                    Screen.PrimaryScreen.Bounds.X,
                    Screen.PrimaryScreen.Bounds.Y,
                    0,
                    0,
                    Screen.PrimaryScreen.Bounds.Size,
                    CopyPixelOperation.SourceCopy
                 );

                string tempDirPath = System.IO.Path.GetTempPath();
                string fileName = String.Format(tempDirPath + "/{0}.jpg",
                    DateTime.Now.ToString()
                    .Replace(":", "_")
                    .Replace(" ", "_")
                    .Replace("/", "_")
                    .Replace("\\", "_"));

                screenShot.Save(fileName, System.Drawing.Imaging.ImageFormat.Jpeg);

                /// send file to server.
                String url = this.txtURL.Text;
                this.uploadFile(url, fileName);
                System.IO.File.Delete(fileName);
            }
            catch (Exception ex)
            {
                MessageBox.Show(this, ex.Message);
            }
            finally
            {
                this.mtxUploadLock.ReleaseMutex();
            }
        }



        private void uploadFile(string url, string file)
        {
            MultipartFormDataContent formData = new MultipartFormDataContent();

            // Build POST variables as a key-value pair array
            KeyValuePair<string, string>[] values =
            {
                new KeyValuePair<string, string>("app", "TigerScreenGrab"),
                new KeyValuePair<string, string>("ver", "1"),
            };

            foreach (KeyValuePair<string, string> pair in values)
            {
                formData.Add(new StringContent(pair.Value), pair.Key);
            }

            ByteArrayContent fileContent = new ByteArrayContent(System.IO.File.ReadAllBytes(file));
            fileContent.Headers.ContentDisposition
                = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
                {
                    FileName = System.IO.Path.GetFileName(file)
                };
            formData.Add(fileContent);

            HttpClient client = new HttpClient();
            HttpResponseMessage result = client.PostAsync(url, formData).Result;
            result.EnsureSuccessStatusCode();
        }

Good Evening.

1 Like

One comment, the mutex implies some form of multi threading however “this” is not thread safe. Always advisable to put it inside an explicit delegate or an anonymous delegate

Thank you sir! I was just reading about that because I wasn’t sure how C# handles timer events and I came across your point. Thank you for pointing that out. Great lesson.

Also you should consider uploading straight from a memory stream instead of creating a physical file then uploading.

Normally find that more cleaner and you dont have to bother about temporary files.

Am still a C# newbie and the only way I could not find a way to convert Bitmap to JPEG in memory other using the Save method. Something to read about I guess.

Btw, wakubwa help me out with an issue I ran using app.config file. I’m getting an error, Object reference not set to an instance of an object.

ConnectionStringSettings conSettings = ConfigurationManager.ConnectionStrings…
string ConnectionString = conSettings.ConnectionString

Provide some context. I think ConfigurationManager.ConnectionStrings does not return what you think it does.
Is this C#? I understand that you store settings in Properties in C# (Properties.Settings.Default.{} ).

It’s c#, n I’m trying to avoid hardcoding the connection string to the dB by using the app.config file but I’m running into the error. When I hardcode the same it works but fails when calling the config file

@bouss that error message does not seem to be configuration manager related, context and app.config are necessary for us to be able to help

I’ll copy the code here once niko kwa comp…

@bouss are you trying to instantiate the configuration manager in your connection method. Correct usage is as described by @TerribleWaste

Should be
.Properties.Settings.Default.

[SIZE=1]

[/SIZE]
hizi ni ngeli gani??

c#

kumbe hii button ya post reply inawork