Question : Unlocking file in WPF

Hi,

I am building a WPF application based on some Windows Forms code. It is a scanning application in which the scanner scans and stor the image in a temporary file. When the application does the next scan this file needs to be deleted and for that it needs to be released. I have the code for this in Windows Forms but I dont know how to do it in WPF. Take look in the end of the code I attached.

I have attached the code for Winows Forms and my code for WPF.

Best regards
RTSol
Code Snippet:
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:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
140:
141:
142:
143:
144:
145:
146:
147:
148:
149:
150:
151:
152:
153:
154:
155:
156:
157:
158:
159:
160:
161:
162:
163:
164:
165:
166:
167:
168:
169:
170:
171:
172:
173:
174:
175:
176:
177:
178:
179:
180:
181:
182:
183:
184:
185:
186:
187:
188:
189:
190:
191:
192:
193:
194:
195:
196:
197:
//The scanning part of the Windows Forms code:
 
        private void menuFileAcquire_Click(object sender, System.EventArgs e)
        {
            WiaClass wiaManager = null;		// WIA manager COM object
            CollectionClass wiaDevs = null;		// WIA devices collection COM object
            ItemClass wiaRoot = null;		// WIA root device COM object
            CollectionClass wiaPics = null;		// WIA collection COM object
            ItemClass wiaItem = null;		// WIA image COM object
 
            try
            {
                wiaManager = new WiaClass();		// create COM instance of WIA manager
 
                wiaDevs = wiaManager.Devices as CollectionClass;			// call Wia.Devices to get all devices
                if ((wiaDevs == null) || (wiaDevs.Count == 0))
                {
                    MessageBox.Show(this, "No WIA devices found!", "WIA", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                    Application.Exit();
                    return;
                }
 
                object selectUsingUI = System.Reflection.Missing.Value;			// = Nothing
                wiaRoot = (ItemClass)wiaManager.Create(ref selectUsingUI);	// let user select device
                if (wiaRoot == null)											// nothing to do
                    return;
 
                // this call shows the common WIA dialog to let the user select a picture:
                wiaPics = wiaRoot.GetItemsFromUI(WiaFlag.SingleImage, WiaIntent.ImageTypeColor) as CollectionClass;
                if (wiaPics == null)
                    return;
 
                bool takeFirst = true;						// this sample uses only one single picture
                foreach (object wiaObj in wiaPics)			// enumerate all the pictures the user selected
                {
                    if (takeFirst)
                    {
                        DisposeImage();						// remove previous picture
                        wiaItem = (ItemClass)Marshal.CreateWrapperOfType(wiaObj, typeof(ItemClass));
                        imageFileName = Path.GetTempFileName();				// create temporary file for image
                        Cursor.Current = Cursors.WaitCursor;				// could take some time
                        this.Refresh();
                        wiaItem.Transfer(imageFileName, false);			// transfer picture to our temporary file
                        pictureBox.Image = Image.FromFile(imageFileName);	// create Image instance from file
                        menuFileSaveAs.Enabled = true;						// enable "Save as" menu entry
                        takeFirst = false;									// first and only one done.
                    }
                    Marshal.ReleaseComObject(wiaObj);					// release enumerated COM object
                }
            }
            catch (Exception ee)
            {
                MessageBox.Show(this, "Acquire from WIA Imaging failed\r\n" + ee.Message, "WIA", MessageBoxButtons.OK, MessageBoxIcon.Stop);
                Application.Exit();
            }
            finally
            {
                if (wiaItem != null)
                    Marshal.ReleaseComObject(wiaItem);		// release WIA image COM object
                if (wiaPics != null)
                    Marshal.ReleaseComObject(wiaPics);		// release WIA collection COM object
                if (wiaRoot != null)
                    Marshal.ReleaseComObject(wiaRoot);		// release WIA root device COM object
                if (wiaDevs != null)
                    Marshal.ReleaseComObject(wiaDevs);		// release WIA devices collection COM object
                if (wiaManager != null)
                    Marshal.ReleaseComObject(wiaManager);		// release WIA manager COM object
                Cursor.Current = Cursors.Default;				// restore cursor
            }
        }
 
//The file disposing in Windows Forms:
 
        ///  temporary image file. 
        private string imageFileName;
 
        ///  Remove image from screen, dispose object and delete the temporary file. 
        private void DisposeImage()
        {
            menuFileSaveAs.Enabled = false;				// disable "Save As" menu entry
            Image oldImg = pictureBox.Image;
            pictureBox.Image = null;					// empty picture box
            if (oldImg != null)
                oldImg.Dispose();						// dispose old image (free memory, unlock file)
 
            if (imageFileName != null)
            {				// try to delete the temporary image file
                try
                {
                    File.Delete(imageFileName);
                }
                catch (Exception)
                { }
            }
        }
 
//The scanning part in the WPF code:
 
        private void scanFile()
        {
            WiaClass wiaManager = null;		// WIA manager COM object
            CollectionClass wiaDevs = null;		// WIA devices collection COM object
            ItemClass wiaRoot = null;		// WIA root device COM object
            CollectionClass wiaPics = null;		// WIA collection COM object
            ItemClass wiaItem = null;		// WIA image COM object
 
            try
            {
                wiaManager = new WiaClass();		// create COM instance of WIA manager
 
                wiaDevs = wiaManager.Devices as CollectionClass;			// call Wia.Devices to get all devices
                if ((wiaDevs == null) || (wiaDevs.Count == 0))
                {
                    MessageBox.Show(this, "No WIA devices found!", "WIA", MessageBoxButton.OK, MessageBoxImage.Stop);
                    Application.Current.Shutdown();
                    return;
                }
 
                object selectUsingUI = System.Reflection.Missing.Value;			// = Nothing
                wiaRoot = (ItemClass)wiaManager.Create(ref selectUsingUI);	    // let user select device
                if (wiaRoot == null)											// nothing to do
                    return;
 
                // this call shows the common WIA dialog to let the user select a picture:
                wiaPics = wiaRoot.GetItemsFromUI(WiaFlag.SingleImage, WiaIntent.ImageTypeColor) as CollectionClass;
                if (wiaPics == null)
                    return;
 
                object wiaObj = wiaPics[0];
                DisposeImage();						                                                // remove previous picture
                wiaItem = (ItemClass)Marshal.CreateWrapperOfType(wiaObj, typeof(ItemClass));
                imageFileName = "C:\\Temp\\tmp2F6D.tmp";				                            // create temporary file for image
                Cursor = Cursors.Wait;				                                                // could take some time
                //this.Refresh();
                wiaItem.Transfer(imageFileName, false);			                                    // transfer picture to our temporary file
 
                BitmapImage bitmap = new BitmapImage();
                bitmap.BeginInit();
                bitmap.UriSource = new Uri(imageFileName);
                bitmap.EndInit();
                scannedImage.Source = bitmap;
 
                Marshal.ReleaseComObject(wiaObj);					                                // release enumerated COM object
            }
            catch (Exception ee)
            {
                MessageBox.Show(this, "Acquire from WIA Imaging failed\r\n" + ee.Message, "WIA", MessageBoxButton.OK, MessageBoxImage.Stop);
                Application.Current.Shutdown();
            }
            finally
            {
                if (wiaItem != null)
                    Marshal.ReleaseComObject(wiaItem);		// release WIA image COM object
                if (wiaPics != null)
                    Marshal.ReleaseComObject(wiaPics);		// release WIA collection COM object
                if (wiaRoot != null)
                    Marshal.ReleaseComObject(wiaRoot);		// release WIA root device COM object
                if (wiaDevs != null)
                    Marshal.ReleaseComObject(wiaDevs);		// release WIA devices collection COM object
                if (wiaManager != null)
                    Marshal.ReleaseComObject(wiaManager);	// release WIA manager COM object
                Cursor = Cursors.Arrow;				        // restore cursor
            }
        }
 
//The file disposing in WPF - here I need help!:
 
        ///  temporary image file. 
        private string imageFileName;
 
        ///  Remove image from screen, dispose object and delete the temporary file. 
        private void DisposeImage()
        {
            //This is the Windows Forms code. The WPF image name is scannedImage
                //menuFileSaveAs.Enabled = false;				// disable "Save As" menu entry
                //Image oldImg = pictureBox.Image;
                //pictureBox.Image = null;					// empty picture box
                //if (oldImg != null)
                //    oldImg.Dispose();						// dispose old image (free memory, unlock file)
            //
 
            scannedImage.Source = null;                 // empty the WPF image
 
            //Here I need to do something similar to oldImg.Dispose();
 
            if (imageFileName != null)
            {				// try to delete the temporary image file
                try
                {
                    File.Delete(imageFileName);
                }
                catch (Exception e)
                {
                    string ex = e.Message;
                }
            }
        }

Answer : Unlocking file in WPF

hi, what you can do is in the first place use the images in WPF without locking them. I found this example which is a method that will return an in-memory copy of your file (see code).

You could also use the CacheOption parameter of BitmapImage and set it to "OnLoad". In xaml:

         
            />
         

     

or in code behind:
BitmapImage bmp = new BitmapImage();
bmp.BeginInit();
bmp.UriSource = new Uri("c:\myImage.png");
bmp.CacheOption = BitmapCacheOption.OnLoad;
bmp.EndInit();

Hope this helps :) !
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 ImageSource GetLockFreeImageSource(String imagePath)
{
    // open stream
    StreamReader reader = new StreamReader(imagePath);
    
    // read stream
    Int32 length = Convert.ToInt32(reader.BaseStream.Length);
    Byte[] data = new Byte[length];
    reader.BaseStream.Read(data, 0, length);
 
    // create image from memory stream's copy
    MemoryStream stream = new MemoryStream(data);
    BitmapImage image = new BitmapImage();
    image.BeginInit();
    image.StreamSource = stream;
    image.EndInit();
    reader.Close();
 
    // free ressources
    reader.Dispose();
    reader = null;
    data = null;
    stream = null;
 
    return image;
}
Random Solutions  
 
programming4us programming4us