• 0

File Access Question (C#)


Question

Hello everyone.

I have an application that zips up some files and then attempts to send that in an e-mail as an attachment.

I have noticed that if the zip file is small it works fine (A few KB's), but the zip is generally between 1 and 2 MB's, and at that size (Which is still rather small) it fails. I get an error that it failed due to the target of an invocation.

I'm assuming that perhaps the zip file is not being released prior to the e-mail being generated when it's larger? I have both the zip creation and e-mail generation in their own backGroundWorkers.

I've been working on this for a good while now, and it doesn't seem to matter if my AntiVirus is running (I thought maybe it was trying to scan the zip), if I do a thread.Sleep, if I choose to send the mail upon the click of another button, etc. In fact, curiously, I created a test application that ONLY sends the zip file. This works perfectly. However, if I use my main application to create the zip file, this test application will be unable to send the zip until after the main application is closed. I really think that the file is not being released, but I don't know why, or from what. The backgroundWorker that is creating the zip is completing successfully (That is where I was originally calling the SendMail event).

My question is what the suggested course of action would be for doing something like this. I've never had an issue with accessing a file like this before.

I really appreciate any suggestions anyone may have for this. I can post whatever code you want, but there's a lot of it, so I'm not sure what all you would want.

Thanks Again,

Link to comment
https://www.neowin.net/forum/topic/846100-file-access-question-c/
Share on other sites

11 answers to this question

Recommended Posts

  • 0

My first train of thought would be to remove it from the backgroundworker and just run the whole thing in a single thread, see if that makes a difference. I would say its worth having a look at your code too and making sure that you're releasing any file handles that you're creating in the process.

Might be worth posting some relevant code (if you can) so we can take a look.

  • 0
what is you're code for creating the zip file?

i like to use the ShapZipLib .NET Zip Library personally, have you given that a go?

can't really do much without knowing what your code is up to so, i await the response :)

Thank you very much for your response. I haven't tried that. I've been using DotNetZip Library (http://dotnetzip.codeplex.com/). It's been really good, and after mentioning this to the developer, it doesn't appear to be related to any of DotNetZip's code...

Here is the code for creating the zip:

		void CompileZip()
		{
			try
			string tempFolder = Path.GetTempPath();
			if (File.Exists(tempFolder + @"\JobFile.zip"))
			{
					SendMail()
			 }
			 else
			 {
					string[] tempDirectory = { tempFolder };
					CompileZipbackgroundWorker2.RunWorkerAsync(tempDirectory);
					Application.DoEvents();
			 }
		}

		private void CompileZipbackgroundWorker2_DoWork(object sender, DoWorkEventArgs e)
		{
			BackgroundWorker worker = sender as BackgroundWorker;
			string[] tempDirectory = (string[])e.Argument;
			string FilePath = tempDirectory[0].ToString();

			string current = Directory.GetCurrentDirectory();
			System.IO.Directory.SetCurrentDirectory(FilePath);

			//int progress = 10;

			using (ZipFile zip = new ZipFile())
			{
				//Add Generated Files to zip
				zip.AddItem("JobFile");
				zip.AddItem("Resources");

				worker.ReportProgress(20);
				worker.ReportProgress(90);

				//Save the zip
				zip.Save(Path.Combine(FilePath, "JobFile.zip"));
			}
			Application.DoEvents();
			worker.ReportProgress(100);
			System.IO.Directory.SetCurrentDirectory(current);
		}

		private void CompileZipbackgroundWorker2_ProgressChanged(object sender, ProgressChangedEventArgs e)
		{
			SubProgressBar1.Value = e.ProgressPercentage;
		}

		private void CompileZipbackgroundWorker2_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
		{
			if ((e.Cancelled == true))
			{
				MessageBox.Show("Canceled", "Error", MessageBoxButtons.OK);
			}

			else if (!(e.Error == null))
			{
				MessageBox.Show(e.Error.Message, "Error", MessageBoxButtons.OK);
			}

			else
			{
				string tempFolder = Path.GetTempPath();
				string zipedFile = tempFolder + @"\JobFile.zip";
				if (File.Exists(zipedFile))
				{
					try
					{
						SubProgressBar1.Style = ProgressBarStyle.Continuous;

						SendMail();
					}
					catch (Exception ex)
					{
						MessageBox.Show(ex.Error.Message, "Error", MessageBoxButtons.OK);

						return;
					}
				}
			}
		}

Here's the code for sending the E-Mail:

		void SendMail()
		{
			try
			{
				SubProgressBar1.Style = ProgressBarStyle.Marquee;

				string ccState = "";
				if (CCCheckBox1.Checked == true)
				{
					ccState = "true";
				}
				else
				{
					ccState = "false";
				}

				string urgentState = null;
				if (UrgentCheckBox1.Checked == true)
				{
					urgentState = "true";
				}
				else
				{
					urgentState = "false";
				}

				string attachState = null;
				if (SubmitStepTB1.Text == "Attach")
				{
					attachState = "true";
				}
				else
				{
					attachState = "false";
				}

				string[] SendMail = { CustLastNameTB1.Text, CustFirstNameTB1.Text, UserCB1.Text, UserEMailTB1.Text, AssemblyVersion, JobFileNotesTB1.Text, ccState, urgentState, attachState };
				SendMailbackgroundWorker1.RunWorkerAsync(SendMail);
			}
			catch
			{

			}
		}

		private void SendMailbackgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
		{
			try
			{
				string[] SendMail = (string[])e.Argument;
				string CustLastName = SendMail[0].ToString();
				string CustFirstName = SendMail[1].ToString();
				string User = SendMail[2].ToString();
				string UserEMail = SendMail[3].ToString();
				string SoftVersion = SendMail[4].ToString();
				string JobFileNotes = SendMail[5].ToString();
				string CCState = SendMail[6].ToString();
				string UrgentState = SendMail[7].ToString();
				string attachState = SendMail[8].ToString();

				//Send E-Mail on click of Button
				MailMessage theMailMessage = new MailMessage("FromEMail", "ToEMail");

				BackgroundWorker worker = sender as BackgroundWorker;
				//worker.ReportProgress(25);

				//Generate the message body
				string messageBody = "New Job File Information Added For:  " + CustLastName + ", " + CustFirstName;
				messageBody += Environment.NewLine + "";
				messageBody += Environment.NewLine + "From:  " + User;
				messageBody += Environment.NewLine + "E-Mail:  " + UserEMail + "  (CC'd =  " + CCState + ")";
				messageBody += Environment.NewLine + "";
				messageBody += Environment.NewLine + "Software Version:  " + SoftVersion;
				messageBody += Environment.NewLine + "";
				messageBody += Environment.NewLine + @"\\server\shared\job files\" + CustLastName + ", " + CustFirstName + @"\";
				messageBody += Environment.NewLine + "";
				messageBody += Environment.NewLine + "Notes:  " + JobFileNotes;

				//worker.ReportProgress(50);

				//Set the property of the message body and subject body
				theMailMessage.Body = messageBody;
				theMailMessage.Subject = "New Job File for " + CustLastName + ", " + CustFirstName;

				//Set the CC Property
				if (CCState == "true")
				{
					MailAddress copy = new MailAddress(UserEMail);
					theMailMessage.CC.Add(copy);
				}

				//Set the Urgent Property
				if (UrgentState == "true")
				{
					theMailMessage.Priority = MailPriority.High;
				}

				//Set the Attachment Property
				if (attachState == "true")
				{
					string tempFolder = Path.GetTempPath();
					theMailMessage.Attachments.Add(new Attachment(tempFolder + @"\JobFile.zip"));
				}

				//worker.ReportProgress(75);

				//E-Mail Credentials and Sending
				SmtpClient theClient = new SmtpClient("smtp.1and1.com");
				System.Net.NetworkCredential theCredential = new
				System.Net.NetworkCredential("FromEMail", "Password");
				theClient.Credentials = theCredential;
				theClient.Send(theMailMessage);

				//worker.ReportProgress(100);
			}
			catch
			{
				MessageBox.Show("The Mail Message was unable to be sent.", "Error", MessageBoxButtons.OK);
			}
		}

		private void SendMailbackgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
		{
			SubProgressBar1.Value = e.ProgressPercentage;
		}

		private void SendMailbackgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
		{
			SubProgressBar1.Increment(100);

			Application.DoEvents();
		}

That should be everything. I'm curious what your thoughts might be. The SendMail code does work (As evidenced by the test project I created), but not if the file has just been created.

Thanks Again. If there is anything else you might want to look at, please let me know. I really, REALLY appreciate the help. I'm just completely out of ideas here and it's driving me nuts...

Edited by M_Lyons10
  • 0

Thank you very much for the suggestion. I will try that to see if it is able to send the mail, but the reason I had initially used a backgroundWorker was because the UI was locking up. Additionally, as the zip process takes some time, the code was attempting to send the mail prior to the zip being completed.

Thanks Again,

  • 0
yeah i understand why the background process is there, but i think for the purposes of working out whats wrong it should be chopped.

it might also be related to having one end background process call another background process.. but i'm unsure

Thanks for your help and everything. I did rewrite the code yesterday / last night and was testing it. It locks up the UI something fierce, but it does work. So, the backgroundWorker is not terminating? Or is somehow holding onto the file? I thought that when a backgroundWorker completed it was done / terminated. I'm not sure what the difference would possibly be. I had run the application a bit ago while watching the file access of the zip file using Process Monitor and it was closing...

You say it's the "sendmail" that's failing. Many ISPs restrict the size of e-mails, so it's possible it's being rejected by the server because the payload is too large.

I realize that some do restrict attachment size, but I've never seen such a small limit (1 - 2 MB's). Just to test that though, I did make a test application that sends the zip file that has already been compiled. It works perfectly so long as the application that created the zip has exited.

Thanks Again,

  • 0

first thing first ... if you get an exception and you are working with backgroundworkers, check the InnerException property - it should encapsulate what exception was raised in the background worker.

Secondly, since you have your send mail worker code wrapped up nicely in a try...catch clause, your assumption that the file is not release properly is void (+ the fact that you are using "using" clause when building the zip file helps in that it will release any stuff used by ZipFile immediatly (if coded properly by the DotNetZip dev))

I "tried" to replicate as close as possible the requirements of the code you posted (basically a progress bar, a button and a few checkboxes) to try to replicate the issue, and from what I can tell, you are trying to Increment the progress bar value when it is in Marquee Mode.

Hinty: Its a good idea to use BackgroundWorker for these kind of situations - situations that involve a UI and length operations so stick to it :) Just when you are handling exceptions, try not to use catch-all exception handlers so that if there is some serious "unhandled" stuff going on in your worker, an exception will be raised, and that can help you out to find the cause and fix it.

  • 0
first thing first ... if you get an exception and you are working with backgroundworkers, check the InnerException property - it should encapsulate what exception was raised in the background worker.

Secondly, since you have your send mail worker code wrapped up nicely in a try...catch clause, your assumption that the file is not release properly is void (+ the fact that you are using "using" clause when building the zip file helps in that it will release any stuff used by ZipFile immediatly (if coded properly by the DotNetZip dev))

I "tried" to replicate as close as possible the requirements of the code you posted (basically a progress bar, a button and a few checkboxes) to try to replicate the issue, and from what I can tell, you are trying to Increment the progress bar value when it is in Marquee Mode.

Hinty: Its a good idea to use BackgroundWorker for these kind of situations - situations that involve a UI and length operations so stick to it :) Just when you are handling exceptions, try not to use catch-all exception handlers so that if there is some serious "unhandled" stuff going on in your worker, an exception will be raised, and that can help you out to find the cause and fix it.

Thank you very much for your response. I will take a look at the InnerException property. I will look into the progressBar increment as well. That may have been an error on my part. The error being thrown the Visual Studio is that the mail message timed out. I will try to improve the catches to help a bit further. It's an odd error and I am not sure what the solution would really be. Programs perform processes like this all the time, but it's really giving me a headache.

This topic is now closed to further replies.
  • Recently Browsing   0 members

    • No registered users viewing this page.
  • Posts

    • Disabling open on hover, great! That was so stupid! They need to do a fix, where if a network share is disconnected, it doesn't hang when opening "This PC" for 20 seconds.
    • Microsoft releases major feature updates for stock Windows 11 apps by Taras Buria In addition to releasing new Windows 11 preview builds, Microsoft announced that inbox Windows apps now have dedicated release notes in the official documentation. At long last, users have access to all the release notes for each app, with changes listed in chronological order. Microsoft used to announce feature updates for stock apps with each build. Now, with Windows Insider release notes hosted on the Microsoft Learn website, each app has a dedicated space for its changelog, which is very useful for those who want to track new features and improvements. Alongside that, Microsoft dropped massive feature updates for six stock apps: Clock, Media Player, Calculator, Voice Recorder, Photos, and Paint. Each app packs quite a lot of changes and new capabilities, so here are the release notes. Here are quick notes so that you can jump to the app you are interested in the most: Calculator Camera Clock Media Player Paint Photos Sound Recorder Here is what is new for the Calculator in version 11.2605.9.0: More accurate square-root results — Fixed rare cases where a calculation that should equal zero (like sqrt(2.25) - 1.5) returned a tiny leftover value instead. Readable text in High Contrast themes — Settings text now shows the correct colors in the High Contrast Aquatic and Desert themes. Fixed layout for right-to-left languages — For languages like Arabic and Hebrew, the graph, number pad, equation fields, and scroll buttons now appear correctly oriented. Reliable launch after upgrading — Fixed an issue where upgrading from much older versions could leave outdated settings that stopped the app from opening. Here is what is new for the Camera app (version 2026.2605.7.0): Zoom slider works on more cameras — The zoom slider now works on the latest cameras, respects your system zoom settings, and updates instantly when you change those settings. Full range of zoom levels — Fixed an issue where the zoom slider only showed three steps on some devices that zoom in finer increments. Front camera works on more devices — Resolved a problem that blocked the front-facing camera on certain wide-angle devices. More video resolution choices — You can now pick video resolutions that were previously hidden; the app shows a heads-up warning instead of removing them. QR links you can still use — When a scanned QR code points to something with no matching app, the link is now copied to your clipboard (with a notification) while still offering a Store search. Smarter default settings — When you haven't set a preference, the app now follows your system settings by default. The Clock app has a massive changelog with the following improvements in version 11.2605.9.0: Timers keep counting after they hit zero — When a timer runs out, it now keeps counting up (for example, -00:27:31) so you can see how far past the time you've gone. You can turn off the daily goal — Focus Sessions now include an "Off" option so you can skip setting a daily goal entirely. New 15-minute snooze option — Alarms now offer a 15-minute snooze interval. Run up to 3 countdowns at once — The Countdown Widget now supports three simultaneous countdowns, up from two. Timer Widget notifications now appear — Fixed an issue where the "timer finished" notification didn't show when the timer was started from the widget. Less clutter in Focus Sessions — Tasks you've already completed no longer show up in the Focus Session task list. More accurate focus progress — Fixed a rounding issue that could show your daily focus progress as a minute short (for example, 49 minutes instead of 50). Smoother World Clock comparisons — The World Clock compare page now loads dates as you scroll, so it feels more responsive. Up-to-date World Clock locations — Refreshed country and city names to match their current names. Correct sun and moon icons during midnight sun — Fixed an icon that wrongly showed a moon during all-day daylight in polar regions. Fixed back-button behavior in clock comparisons — Pressing back once now takes you back as expected, instead of jumping the date to 1926. Corrected the Newfoundland time zone — Newfoundland now uses the right time zone (St. John's). Disabled alarms stay looking disabled — Editing a turned-off alarm no longer makes it appear turned on. Cleaner timer cards — The expand button is now turned off on timer cards that have no time set, preventing actions that wouldn't do anything. Clearer theme setting — Updated the wording to "Choose your preferred app theme." Smoother Settings links — The "About" links in Settings no longer trigger an unexpected "switch apps" prompt. Fixed spacing in Spotify settings — Corrected uneven spacing in the Spotify settings card. Better focus visibility in High Contrast — The focus highlight in World Clock is now clearly visible in the High Contrast Aquatic and Desert themes. No more double announcements — Screen readers no longer read the timer value twice. Countdown names read correctly — Screen readers now properly announce the name of each countdown. Keyboard focus stays put — Focus no longer disappears after you press the Timer Reset button. Clearer alarm toggle for screen readers — Tidied up how the alarm on/off switch is announced. The Media Player app received plenty of changes as well (version 11.2605.14.0): Custom captions — You can now personalize how closed captions appear, with caption styling tied to your Windows caption settings, plus a quick link to open those settings directly. "Indexing" banner in the play queue — When your media library is still being scanned, a banner now explains why some items may not appear yet. Fixed the look of selected items — Corrected a layout glitch with selected items in lists. Fewer playback failures — Improved how the app recognizes supported file types, so more files play without issues. Playlists need a name — You can no longer accidentally save a playlist with a blank name. Cleaner look for empty playlists — Improved how a playlist appears when it has no items yet. More stable play queue edits — Fixed a crash that could happen when changing the play queue while the app was switching between sessions. Clearer "missing codec" message — Improved the dialog that appears when a file needs a codec you don't have, with clearer guidance on what to do. A big update is also available for Paint in version 11.2605.61.0: Adjustable eraser transparency — You can now control how transparent the eraser is. Cleaner stamp brush strokes — Fixed visible color shifts and artifacts when using stamp-style brushes. JPEG photos save in place — Opening a rotated JPEG and pressing Save now overwrites the original instead of unexpectedly prompting "Save As." No more crash on bad image files — Opening a damaged or invalid image, from within the app, by double click, or commandline, now shows a clear error message instead of closing the app. Classic selection behavior restored — The selection outline now hides while you move, resize, or rotate a selection, just like in classic Paint. Tidier AI image panel — Fixed missing spacing at the bottom of the AI image generation panel for a cleaner layout. Visible button hover in light theme — Toolbar split buttons now show a clear hover highlight in the light theme. Snappier toolbar — Streamlined how the ribbon lays out, giving a small speed boost at startup. Fewer background crashes — Fixed a crash that could happen while background tasks were finishing up. Stable app shutdown — Prevented rare crashes when closing the app. Fixed layer removal glitch — Deleting the active layer no longer leaves the layers list in an inconsistent state. Here is what is new in the Photos app (version 2026.11060.2004.0): AI watermarking — AI-generated or edited images can now carry a visible Copilot watermark. You choose Never, Always, or Ask Every Time in Settings, with a confirmation when saving. The watermarking is off by default in settings. Better viewing of small images and pixel art — Tiny images (like 16×16 pixel art) now zoom in far more to fill the screen and stay crisp instead of looking blurry. Select scanned text with the keyboard — When text is detected in an image, you can now navigate and select it using the arrow keys, Shift+Arrow, Home/End, and Ctrl+A, with a clear focus highlight. Fixed a crash in text recognition — Resolved a crash that could close Photos while detecting text in images; the app now recovers gracefully. Easier keyboard navigation — Tabbing through the navigation bar no longer stops on hidden controls, so it takes a single Tab to move past it instead of three. And finally, here is the Sound Recorder (version 11.2605.1.0): Waveform shows with Bluetooth mics — The live waveform now displays correctly when you record using a Bluetooth audio device. No more stray scrollbar — A non-working horizontal scrollbar no longer appears at the bottom of the waveform unless you've zoomed in. Mark button ready right away — The Mark button no longer looks grayed out until you hover over it after opening the app. Markers hidden for WAV files — Markers are now turned off for WAV recordings, since that format can't store them — so they're no longer lost silently. Smoother deleting — Quickly pressing Delete and Enter to remove several recordings in a row no longer triggers a "file doesn't exist" error. Fixed a memory issue — Resolved a memory leak that occurred each time a recording started. You can find all these changelogs in the official documentation here.
    • again, an article about Microsoft Edge and ridicules hater's comments
    • From this very same article: "For organizations that prefer a “more deliberate pace”, the Extended Stable channel remains an option."
    • Or every other browser, because they all behave the same, at least the mainstream ones. Firefox does exactly the same: background updates, restart to install them. Haters gotta hate, I guess.
  • Recent Achievements

    • Very Popular
      AndrewSteel earned a badge
      Very Popular
    • Veteran
      Taliseian went up a rank
      Veteran
    • One Month Later
      Clizby earned a badge
      One Month Later
    • One Month Later
      Timaximus earned a badge
      One Month Later
    • Week One Done
      Timaximus earned a badge
      Week One Done
  • Popular Contributors

    1. 1
      +primortal
      499
    2. 2
      PsYcHoKiLLa
      170
    3. 3
      +Edouard
      162
    4. 4
      Steven P.
      85
    5. 5
      ATLien_0
      77
  • Tell a friend

    Love Neowin? Tell a friend!