webbrowsercontrol issue, clear cache not working? - c#

I'm using a webbrowsercontrol to show .pdf's stored locally. At button press I want the webbrowser to show an empty page/nothing and I want to move the .pdf to a different folder. First I tried navigating to "" before moving but my .pdf was used by another process. Google told me that I probably needed to clear the browser's cache to be able to move it. I did so using the code found here: http://www.gutgames.com/post/Clearing-the-Cache-of-a-WebBrowser-Control.aspx and I even tried the alternative code line found in comment nr 2, but none of these let me move my .pdf, it's still used by another process.
What can/should I do to be able to move the file? Have I forgotten something?
At the second File.Move is where I get the error:
webBrowser1.Navigate("");
WebBrowserHelper.ClearCache();
if (calConv != "")
{
File.Move(forsDir + calConv + ".cal", forsDir + calConv.Replace("ToDo\\", "") + ".cg4");
File.Move(forsDir + calConv + ".pdf", forsDir + calConv.Replace("ToDo\\", "") + ".pdf");
}

This is how to show the PDF without using the webcontrol, using Adobe Reader instead:
Download the Acrobat SDK from http://www.adobe.com/devnet/acrobat/downloads.html
In your project add a reference to two dlls from the SDK - AxInterop.AcroPDFLib.dll and Interop.AcroPDFLib.dll
In your form's constructor add the Adobe previewer control:
// Check if the user has Adobe Reader installed, if not you could show a link to Adobe Reader installer
if (Type.GetTypeFromProgID("AcroPDF.PDF") == null)
{
pnlGetAdobe.Visible = pnlGetAdobe.Enabled = true;
}
else
{
try
{
// Initialize the Adobe control
axAcroPDF1 = new AxAcroPDF();
axAcroPDF1.Dock = DockStyle.Fill;
axAcroPDF1.Enabled = true;
axAcroPDF1.Location = new Point(0, 25);
axAcroPDF1.Name = "axAcroPDF1";
axAcroPDF1.OcxState = (AxHost.State)new ComponentResourceManager(typeof(JasperPdfReport)).GetObject("axAcroPDF1.OcxState");
axAcroPDF1.Size = new Size(634, 393);
axAcroPDF1.TabIndex = 1;
pnlCenter.Controls.Add(axAcroPDF1); // Add it to a container or instead directly to your form with this.Controls.Add(axAcroPDF1)
axAcroPDF1.BringToFront();
}
catch (COMException cex)
{
axAcroPDF1.Dispose();
axAcroPDF1 = null;
MessageBox.Show(cex.ToString());
}
catch (Exception ex)
{
axAcroPDF1.Dispose();
axAcroPDF1 = null;
MessageBox.Show(ex.ToString());
}
}
And finally load your PDF file into the control:
if (axAcroPDF1 != null && File.Exists(pdfFilename))
{
axAcroPDF1.setShowToolbar(false);
axAcroPDF1.setView("FitH");
axAcroPDF1.setLayoutMode("SinglePage");
// Load the PDF into the control
axAcroPDF1.LoadFile(pdfFilename);
axAcroPDF1.src = pdfFilename;
// Show it
axAcroPDF1.Show();
axAcroPDF1.Refresh();
}

Related

c# adobe acrobat SDK: file is still locked after SDK quit

I'm working with C# and adobe acrobat SDK.
When the program throws an error due to the pdf already being compressed I want to move the pdf.
However, C# complains that the file is being used by another process and I know it has to do with the SDK and not another program.
After some debugging I found out that compressPDFOperation.Execute is the culprit.
How can I close it so that I can move the file?
try {
// Initial setup, create credentials instance.
Console.WriteLine(".json: " + Directory.GetCurrentDirectory() + "/pdftools-api-credentials.json");
Credentials credentials = Credentials.ServiceAccountCredentialsBuilder()
.FromFile(Directory.GetCurrentDirectory() + "/pdftools-api-credentials.json")
.Build();
// Create an ExecutionContext using credentials and create a new operation instance.
ExecutionContext executionContext = ExecutionContext.Create(credentials);
CompressPDFOperation compressPDFOperation = CompressPDFOperation.CreateNew();
// Set operation input from a source file.
FileRef sourceFileRef = FileRef.CreateFromLocalFile(directory + #"\" + pdfname);
compressPDFOperation.SetInput(sourceFileRef);
// Execute the operation.
FileRef result = compressPDFOperation.Execute(executionContext);
// Save the result to the specified location.
//if pdf is part of a group, the group directory name will be stored in fileGroupDirectory
string fileGroupDirectory = directory.Replace(sourceDir, "");
result.SaveAs(finishedDir + fileGroupDirectory + pdfname);
}
catch (ServiceApiException ex)
{
Console.WriteLine("Exception encountered while executing operation", ex.Message);
if (ex.Message.Contains("The input file is already compressed"))
{
File.Move(file, finishedDir + fileGroupDirectory + fileName);
}
}
I've found a solution , it's not best practice but I don't know an other way to do it.
I've declared all the variables used to execute the compression (sourceFileRef, compressPdfOperation, ...) before the try catch statement and after result.SaveAs(...) I set those variables to null and run the garbage collection.
compressPDFOperation = null;
result = null;
sourceFileRef = null;
executionContext = null;
credentials = null;
GC.Collect();

CEFSharp app displays blank screen and then responds on it's own after a minute

I've been working on a app which uses CEFSharp (version 83.4.20) to load my companies VOIP platform (engage.ringcentral.com). The source is up on Github https://github.com/dylanlangston/EngageRC
The app has been working for about a month now and after putting it into production I've received reports of an odd issue. People are seeing a blank screen and unable to interact with the webpage (
Example of issue ). After a few minutes the issue seems to resolve itself and their able to interact with the webpage again. I haven't been able to reproduce the issue myself.
I thought this might be a rendering issue. So far I've tried to adjust the following in my app:
Remove the lines below.
settings.CefCommandLineArgs.Add("disable-gpu");
settings.CefCommandLineArgs.Add("disable-gpu-shader-disk-cache", "1");
Replace them with.
settings.CefCommandLineArgs.Add("disable-gpu-compositing");
Unfortunately this hasn't resolved the issues and I'm unsure what I'm missing.
The relevant code for CEF Initialization is located in https://github.com/dylanlangston/EngageRC/blob/master/Windows/MainWindow.Designer.cs under the InitializeChromium method. See Below
//
// Chrome
//
private CefSharp.WinForms.ChromiumWebBrowser chromeBrowser;
public ChromiumWebBrowser InitializeChromium(string URL, string Name)
{
// Check if already Initialized
if (Cef.IsInitialized == false)
{
CefSettings settings = new CefSettings();
// Enable Logging if debugging or console window
if (!this.debug || !this.console)
{
settings.LogSeverity = LogSeverity.Disable;
}
else
{
settings.LogSeverity = LogSeverity.Verbose;
}
// Enable Microphone settings
settings.CefCommandLineArgs.Add("enable-media-stream", "1");
// Set Custom Browser Paths
settings.CefCommandLineArgs.Add("disable-gpu-shader-disk-cache", "1");
// Disable GPU to fix rendering issues on some machines.
settings.CefCommandLineArgs.Add("disable-gpu");
// Disable CORS protection (cross site scripting) which the engage.ringcentral.com site doesn't seem to like/respect, disabled as the website doesn't seem to improve with this turned on.
//settings.CefCommandLineArgs.Add("disable-web-security");
// Enable session Cookie persistence, disabled as it's unneeded.
//settings.PersistSessionCookies = true;
// Custom Browser paths
settings.BrowserSubprocessPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Resources\CEFSharp\CefSharp.BrowserSubprocess.exe");
settings.LocalesDirPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Resources\CEFSharp\locales\");
settings.ResourcesDirPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Resources\CEFSharp\");
// Check if Resources folder is writable. If it isn't then write to application data.
DirectoryInfo di = new DirectoryInfo(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Resources\CEFSharp\"));
if ((di.Attributes & FileAttributes.ReadOnly) == FileAttributes.ReadOnly)
{
settings.RootCachePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), #"EngageRC\CEFSharp\cache");
settings.CachePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), #"EngageRC\CEFSharp\cache");
settings.LogFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), #"EngageRC\CEFSharp\debug.log");
}
else
{
settings.RootCachePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Resources\CEFSharp\cache");
settings.CachePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Resources\CEFSharp\cache");
settings.LogFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Resources\CEFSharp\debug.log");
}
// Initialize cef with the provided settings or add new tab
Cef.Initialize(settings, performDependencyCheck: true, browserProcessHandler: null);
}
// Create a browser component
chromeBrowser = new ChromiumWebBrowser(URL);
// Set Name
chromeBrowser.Name = Name;
// Adjust size and scaling
this.chromeBrowser.Dock = DockStyle.Fill;
this.chromeBrowser.Width = this.Width;
this.chromeBrowser.Height = this.Height;
// Add control
this.Controls.Add(chromeBrowser);
// Bring to front
this.chromeBrowser.BringToFront();
// Set label to Goodbye.
this.label1.Text = "Goodbye";
// Return control
return chromeBrowser;
}
I wasn't able to find any previous questions with my Google foo so it seems this isn't something other's are seeing their applications. I'm still learning the ropes when it comes to C# so it's 100% possible this is my own fault and something I'm doing wrong.
I was able to get verbose logging from a machine that experienced the issue. I'm mostly seeing the following error. Full logs at https://gist.github.com/dylanlangston/194e389ead437e6c6fe08b2d4746bf43
[0729/083616.491:ERROR:paint_controller.cc(646)] PaintController::FinishCycle() completed
Any ideas or recommendations to help troubleshoot this is appreciated!
Updated: Based on #amaitland's helpful comments it seems this behavior may be caused by using Thread.Sleep on a thread on I'm not supposed to.
After reviewing my code it looks like I have this in two locations.
First I call thread.sleep to wait until the browsers zoom level matches the value I've saved to the windows isolatedstorage. This shouldn't be running except when the application first starts. I don't think this is the problem but I am posting it here anyways to be safe. (https://github.com/dylanlangston/EngageRC/blob/master/CEFSharpHandlers.cs)
public void OnLoadingStateChanged(object sender, LoadingStateChangedEventArgs args)
{
ChromiumWebBrowser chrome = (ChromiumWebBrowser)sender;
if (!args.IsLoading) // Loading finished.
{
// If first load set zoom level to previous level
if (firstLoad < 3)
{
try
{
double zoom = double.Parse(ConfigReader.ReadIsolatedStorage("z"), System.Globalization.CultureInfo.InvariantCulture);
while (args.Browser.GetZoomLevelAsync().Result != zoom) { chrome.SetZoomLevel(zoom); Thread.Sleep(50); }
}
catch { }
firstLoad++;
}
// These JS and CSS modifications built into EngageRC
string hotfixJS = "";
string hotfixCSS = "/* Fix for dropdowns */ ul.dropdown-menu[style=\\\"opacity: 1;\\\"] {display: block !important; } /* End fix for dropdowns */";
// Inject custom javascript and css code on page load
chrome.ExecuteScriptAsync(hotfixJS);
chrome.ExecuteScriptAsync("var engageRCSS = document.getElementById('EngageRCSS'); if (!engageRCSS) { var node = document.createElement('style'); node.setAttribute('id', 'EngageRCSS'); node.innerHTML = \"" + hotfixCSS +"\"; document.body.appendChild(node); }");
if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Resources\Custom.js"))) { chrome.ExecuteScriptAsync(System.IO.File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Resources\Custom.js"))); }
if (File.Exists(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Resources\Custom.css"))) { chrome.ExecuteScriptAsync("var customCSS = document.getElementById('customcss'); if (!customCSS) { var node = document.createElement('style'); node.setAttribute('id', 'customcss'); node.innerHTML = \"" + System.IO.File.ReadAllText(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, #"Resources\Custom.css")).Replace("\n", String.Empty).Replace("\r", String.Empty).Replace("\t", String.Empty).Replace("\"", "\\\"") + "\"; document.body.appendChild(node); }"); }
}
}
I also have it when displaying a notification. This is most likely my problem as this is running in the main application thread... (https://github.com/dylanlangston/EngageRC/blob/master/NotificationSupport.cs)
public void displayNotification(string Title = "EngageRC", string Message = "")
{
// Display notification for 5 seconds
Notify notification = MainWindow.notification;
try
{
if (!IsActive(hWnd)) // Check if application is already active.
{
string config = ConfigReader.GetConfigValue("NotificationsDisabled").ToLower();
if (!(config == "true" || config == "1"))
{
notification.NewNotification(Title, Message, 5000);
}
config = ConfigReader.GetConfigValue("GetFocusOnCallDisabled").ToLower();
if (!(config == "true" || config == "1") && (Message == "You have incoming call"))
{
// Minimize window
ShowWindow(hWnd, 0x02);
// Restore window to previous state.
ShowWindow(hWnd, 0x09);
}
config = ConfigReader.GetConfigValue("GetFocusOnPendingDispositionDisabled").ToLower();
if (!(config == "true" || config == "1") && (Message == "You have a disposition pending"))
{
// Minimize window
ShowWindow(hWnd, 0x02);
// Restore window to previous state.
ShowWindow(hWnd, 0x09);
}
}
}
catch { notification.SetIconVisible(false); }
finally
{
Thread.Sleep(4999);
notification.SetIconVisible(false);
}
}
Based on what I've heard I should make the Notification Form run on a different thread from the main application then? Or am I way off base?
Update:
I was able to move the notification into it's own thread. I'm closing this issue and will have the user's test to see if the blank screen persists.
Thanks for the help again!!
#amaitland's comments were helpful in narrowing this issue down.

"How to make a windows form communicate with Microsoft Office?"

My programs works perfectly with using hotkeys in place to alter text in Microsoft Word, Powerpoint, Excel, and Outlook.
The only problem I have is that the program will not execute unless I either click on it with the mouse or use Alt and Tab to toggle between my program and Microsoft Office programs.
I wish to not use the mouse or use Alt and Tab. I have a keyboard hook script in place to copy the hotkeys, but it will only work if Windows sees my program on top of everything and is active.
I have my program on top of everything, but when going to Microsoft Word (for example), my program is no longer active and Microsoft Word is now active. I would have to go to my program to make it active by clicking on it with my mouse or using Alt and Tab, perform the hotkey and then go back to Microsoft Word with using my mouse to click on it or using Alt and Tab to make it active to use the hotkey that was pressed.
With this, how would I go about and make my program a shared plugin for Microsoft Office, to where when it is running, Microsoft Office will recognize my program?
First of all, you can automate Outlook form other applications. Due to the fact that Outlook is a singleton only one application instance can be run at the same time on the system. So, you may get a running instance from the ROT:
//Get reference to Outlook.Application from the ROT.
oApp = (Outlook.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Outlook.Application");
If there is no Outlook running on the system you may simply create a new one. See C# app automates Outlook (CSAutomateOutlook) for more information.
Here is my code for you to view so you have an idea what I am doing.
Sorry, I tried to put it as a comment, but it was too long.
//MICROSOFT WORD INTEGRATION
try
{
app = (Microsoft.Office.Interop.Word.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Word.Application");
app.ActiveWindow.Selection.Font.Color = (Microsoft.Office.Interop.Word.WdColor)(changeColor.R + 0x100 * changeColor.G + 0x10000 * changeColor.B);
}
catch (System.Exception excp)
{
}
//MICROSOFT EXCEL INTEGRATION
try
{
xlApp = (Microsoft.Office.Interop.Excel.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application");
xlBook = xlApp.ActiveWorkbook;
xlSheet = xlBook.ActiveSheet;
Microsoft.Office.Interop.Excel.Range rngSelection = xlApp.Selection as Microsoft.Office.Interop.Excel.Range;
for (var r = 1; r <= rngSelection.Rows.Count; r++)
{
for (var c = 1; c <= rngSelection.Columns.Count; c++)
{
rngSelection[r, c].Font.Color = copyProgramText.SelectionColor;
}
}
}
catch (System.Exception excp)
{
}
//MICROSOFT POWERPOINT INTEGRATION
try
{
pwptApp = (Microsoft.Office.Interop.PowerPoint.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("PowerPoint.Application");
pwptApp.ActiveWindow.Selection.TextRange.Font.Color.RGB = System.Drawing.ColorTranslator.ToOle(changeColor);
if (pwptApp.ActiveWindow.Selection.TextRange.Text.Trim() == "") pwptApp.ActiveWindow.Selection.TextRange.Text = " ";
}
catch (System.Exception excp)
{
}
//MICROSOFT OUTLOOK INTEGRATION
try
{
Microsoft.Office.Interop.Outlook.Application otlkApp = (Microsoft.Office.Interop.Outlook.Application)System.Runtime.InteropServices.Marshal.GetActiveObject("Outlook.Application");
Microsoft.Office.Interop.Outlook.Explorer otlkExp = otlkApp.ActiveExplorer();
Microsoft.Office.Interop.Outlook.Selection otlkSel = otlkExp.Selection;
Microsoft.Office.Interop.Outlook.MailItem otlkMsg = otlkApp.ActiveInspector().CurrentItem as Microsoft.Office.Interop.Outlook.MailItem;
Microsoft.Office.Interop.Outlook.Inspector insp = otlkMsg.GetInspector;
Microsoft.Office.Interop.Word.Document otlkDoc = (Microsoft.Office.Interop.Word.Document)insp.WordEditor;
string sepSel = otlkDoc.Application.Selection.Text;
byte rColor = changeColor.R;
byte gColor = changeColor.G;
byte bColor = changeColor.B;
if (sepSel.Trim() == "\r") return;
char cReturn = (char)13;
if (sepSel == cReturn.ToString()) return;
if (sepSel != "")
{
otlkMsg.HTMLBody = otlkMsg.HTMLBody.Replace(sepSel, "<font style = 'color: rgb(" + rColor.ToString() + ", " + gColor.ToString() + ", " + bColor.ToString() + ")'>" + sepSel + " </font>");
}
else
{
return;
}
prevOutlookContents = otlkMsg.HTMLBody;
}
catch (System.Exception excp)
{
}

iTextSharp reader javascript error RSS

I found yesterday on google iTextSharp for pdf filling data.
but when i trying to read pdf ,i am not getting acrofields from pdf .
Here is code
private void ListFieldNames()
{
string pdfTemplate = #"E:\Vikas\Projects\PdfWriter\PdfWriter\nbc-app.pdf";
// create a new PDF reader based on the PDF template document
PdfReader pdfReader = new PdfReader(pdfTemplate);
AcroFields formfields = pdfReader.AcroFields;
// create and populate a string builder with each of the
// field names available in the subject PDF
foreach (KeyValuePair<string, AcroFields.Item> de in formfields.Fields)
{
sb.Append(de.Key.ToString() + Environment.NewLine);
}
// Write the string builder's content to the form's textbox
txtbx.TextMode = TextBoxMode.MultiLine;
txtbx.Width = 500;
txtbx.Rows = 40;
txtbx.Text = sb.ToString();
//txtbx.SelectionStart = 0;
}
Than i was doing debugging i saw reader.javascript throwing error (error is below )
if (typeof(this.ADBE) == "undefined")
this.ADBE = new Object();
ADBE.LANGUAGE = "ENU";
ADBE.Viewer_string_Title = "Adobe Acrobat";
ADBE.Viewer_string_Update_Desc = "Adobe Interactive Forms Update";
ADBE.Viewer_string_Update_Reader_Desc = "Adobe Reader 7.0.5";
ADBE.Reader_string_Need_New_Version_Msg = "This PDF file requires a newer version of Adobe Reader. Press OK to download the latest version or see your system administrator.";
ADBE.Viewer_Form_string_Reader_601 = "This PDF form requires a newer version of Adobe Reader. Although the form may appear to work properly, some elements may function improperly or may not appear at all. Press OK to initiate an online update or see your system administrator.";
ADBE.Viewer_Form_string_Reader_Older = "This PDF form requires a newer version of Adobe Reader. Although the form may appear to work properly, some elements may function improperly or may not appear at all. Press OK for online download information or see your system administrator.";
ADBE.Viewer_Form_string_Viewer_601 = "This PDF form requires a newer version of Adobe Acrobat. Although the form may appear to work properly, some elements may function improperly or may not appear at all. Press OK to initiate an online update or see your system administrator.";
ADBE.Viewer_Form_string_Viewer_60 = "This PDF form requires a newer version of Adobe Acrobat. Although the form may appear to work properly, some elements may function improperly or may not appear at all. For more information please copy the following URL (CTRL+C on Win, Command-C on Mac) and paste into your browser or see your system administrator.";
ADBE.Viewer_Form_string_Viewer_Older = "This PDF requires a newer version of Acrobat. Copy this URL and paste into your browser or see your sys admin.";
ADBE.Viewer_Form_string_Reader_5x = "This PDF form requires a newer version of Adobe Reader. Without a newer version, the form may be displayed, but it might not work properly. Some form elements might not be visible at all. If an internet connection is available, clicking OK will open your browser to a web page where you can obtain the latest version.";
ADBE.Viewer_Form_string_Reader_6_7x = "This PDF form requires a newer version of Adobe Reader. Without a newer version, the form may be displayed, but it might not work properly. Some form elements might not be visible at all. If an internet connection is available, clicking OK will download and install the latest version.";
ADBE.Viewer_Form_string_Viewer = "This PDF form requires a newer version of Adobe Acrobat. Without a newer version, the form may be displayed, but it might not work properly. Some form elements might not be visible at all. If an internet connection is available, clicking OK will download and install the latest version.";
if (typeof(ADBE.Reader_Value_Asked) == "undefined")
ADBE.Reader_Value_Asked = false;
if (typeof(ADBE.Viewer_Value_Asked) == "undefined")
ADBE.Viewer_Value_Asked = false;
if (typeof(ADBE.Reader_Need_Version) == "undefined" || ADBE.Reader_Need_Version < 8.1)
{
ADBE.Reader_Need_Version = 8.1;
ADBE.Reader_Value_New_Version_URL = "http://cgi.adobe.com/special/acrobat/update";
ADBE.SYSINFO = "?p=" + app.platform + "&v=" + app.viewerVersion + "&l=" + app.language + "&c=" + app.viewerType + "&r=" + ADBE.Reader_Need_Version;
}
if (typeof(ADBE.Viewer_Need_Version) == "undefined" || ADBE.Viewer_Need_Version < 8.1)
{
ADBE.Viewer_Need_Version = 8.1;
ADBE.Viewer_Value_New_Version_URL = "http://cgi.adobe.com/special/acrobat/update";
ADBE.SYSINFO = "?p=" + app.platform + "&v=" + app.viewerVersion + "&l=" + app.language + "&c=" + app.viewerType + "&r=" + ADBE.Viewer_Need_Version;
}
if (typeof(xfa_installed) == "undefined" || typeof(xfa_version) == "undefined" || xfa_version < 2.6)
{
if (app.viewerType == "Reader")
{
if (ADBE.Reader_Value_Asked != true)
{
if (app.viewerVersion < 8.0)
{
if (app.alert(ADBE.Reader_string_Need_New_Version_Msg, 1, 1) == 1)
this.getURL(ADBE.Reader_Value_New_Version_URL + ADBE.SYSINFO, false);
ADBE.Reader_Value_Asked = true;
}
else if (app.alert(ADBE.Viewer_Form_string_Viewer, 1, 1) == 1)
app.findComponent({cType:"Plugin", cName:"XFA", cVer:"2.6"});
}
}
else
{
if (ADBE.Viewer_Value_Asked != true)
{
if (app.viewerVersion < 7.0)
app.response({cQuestion: ADBE.Viewer_Form_string_Viewer_Older, cDefault: ADBE.Viewer_Value_New_Version_URL + ADBE.SYSINFO, cTitle: ADBE.Viewer_string_Title});
else if (app.viewerVersion < 8.0)
{
if (app.alert(ADBE.Viewer_Form_string_Viewer, 1, 1) == 1)
app.launchURL(ADBE.Viewer_Value_New_Version_URL + ADBE.SYSINFO, true);
}
else if (app.alert(ADBE.Viewer_Form_string_Viewer, 1, 1) == 1)
app.findComponent({cType:"Plugin", cName:"XFA", cVer:"2.6"});
ADBE.Viewer_Value_Asked = true;
}
}
}
how should i fixed this problem ?

IO Exception - File In Use By Another Process

C# / .NET 3.5, WindowsForms.
I have this Windows form that displays an image from a file, and whenever user saves the record this code is executed:
string oldLoc = itemsBO.ImageLoc;
if (oldLoc != SystemSettings.NoImageLocation)
{
if (File.Exists(oldLoc))
{
try { File.Delete(oldLoc); }
catch (IOException ex)
{
MessageBox.Show("1 - " + ex.GetType().ToString() + " " + ex.Message);
}
}
}
string saveLoc = itemsBO.ImageSearchLoc + ".jpg";
if (File.Exists(saveLoc))
{
try { File.Delete(saveLoc); }
catch (IOException ex)
{
MessageBox.Show("2 - " + ex.GetType().ToString() + " " + ex.Message);
}
}
try
{
if (pictureBox2.Image != null)
pictureBox2.Image.Save(saveLoc, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (IOException ex)
{
MessageBox.Show("3 - " + ex.GetType().ToString() + " " + ex.Message);
}
Disregard the poor MessageBox messages, but it errors out in each Catch statement. It can't delete the "existing" Image because it says it's in use by another process. Can't save because a file exists in that same path because it's not deleting.
This is the code that sets the Image when they try to add a new picture;
Image clipImage = Clipboard.GetImage();
if (tabControl2.SelectedTab == tabPage5)
{
pictureBox1.Image = clipImage;
itemsBO.IsDirtyImage = true;
}
else if (tabControl2.SelectedTab == tabPage6)
{
pictureBox2.Image = clipImage;
itemsBO.IsDirtyImage2 = true;
}
Then when the form loads up an existing record with an image, this is the code used to fetch/display it:
byte[] bits = File.ReadAllBytes(imgfil);
msImage = new MemoryStream(bits, 0, bits.Length);
if (tabControl2.SelectedTab == tabPage5)
pictureBox1.Image = Image.FromStream(msImage);
else if (tabControl2.SelectedTab == tabPage6)
pictureBox2.Image = Image.FromStream(msImage);
imgfil being a path to the image, of course.
Absolutely no idea where to begin...
I have this Windows form that displays an image from a file, and whenever user saves the record
If you're still displaying the image when they save the file, the application will still be accessing the file if I'm not mistaken. Try disposing of the file first, probably by setting the picture box's (or whatever you're using to display the image) image to null, or load a blank picture before you perform the operation.
If it says file in use by another process, well then it must be in use by another process :)
Have you tried monitoring the file lock using Process Explorer.
Once you have identified what's holding your file, close that file handle using Process Explorer and then try to run your code.
This might help-
How to find out what processes have folder or file locked?
So I had inherited this application from another user, turns out the pictureBoxes were having their Image set in another chunk of code independent of that third block of code in the original post. It was because of this that the IOException was happening :(

Categories