the process cannot access the file because it is being used by another process in vb.net - vb.net

help me.. i'm new in visual basic....
when i'm running the update it shows the error
The process cannot access the file 'C:\Documents and Settings\Macky\My Documents\Visual Studio 2008\Projects\Marcelo 2.2.3\Marcelo\bin\Debug\Students\MIC953867.jpg' because it is being used by another process.
my code is this
Public Sub copingfile()
If inFileName = Nothing Then
studpic.Image = Nothing
Else
outFileName = inFileName
pos = inFileName.LastIndexOf(".")
If (pos > 0) Then
outFileName = outFileName.Substring(0, pos)
End If
outFileName += ".jpg"
str = Application.StartupPath & "\Students\"
saveJPEGFile.FileName = str & StudID.Text & ".jpg" '& outFileName
fil1.Copy(inFileName, saveJPEGFile.FileName, True) 'the error shows here...
outFileName = saveJPEGFile.FileName()
End If
End Sub
I can save new student information with picture.. but when it comes in updating the picture these codes didn't work......

fil1.Copy(inFileName, saveJPEGFile.FileName, True)
You're attempting overwrite a file that's open or being used. If the file is open in a viewer/editor, then it can't be copied over. Either you opened it manually, or did so through code and it's still "attached" to something running.
If it's not open in a window, try stopping your code and deleting that file manually. If you can, it's pretty obvious something in code is still using it when you get to the line that errored. You'll need to figure out where that file is still being used (Open stream somewhere? Open in VS, itself?), as it doesn't appear to be in the code you provided.

You are going to need to show more code, you are using variables not in your code listing. Plus you do not show the code that originally saves your image.
But here is my guess...are you sure you closed the file when you saved it for the first time? You cannot generally copy to, or from, a file that is open.
(Files can be opened as shared, but I don't think you are doing that).
Post more code if you get a chance.

Related

Update an excel file by multiple users at same time without opening the file

Scenario
I have an excel file that contains data. There are multiple users accessing the file at the same time.
Problem
There will be problem if multiple users tried to input data to that excel file at the same time due to only one user is allowed to open the file at one time
Question
Is there any way whereby I can update the excel file (Eg: add a value to a cell, delete a value from a cell, find a particular cell etc) without opening it so that multiple users can update it at the same time using excel VBA?
I went to the direction of using shared files. But later found out to be excel shared files are very buggy. If use shared file, excel/macro can be very slow, intermittent crashes and sometime the whole file may get corrupted and could not be opened or repaired afterwards. Also depends on how many users use the file, the file size can grow quite big. So it is best not to use shared workbook. Totally not worth trying. Instead if need multiple users to update data simultaneously, it is better to use some database such as MSAccess, MSSql (Update MSSQL from Excel) etc with excel. For my situation since number of users are less, I didn't use any database, instead put a prompt for the user to wait until the other user close that file. Please see the codes below to check if a file is opened and if so, to prompt user. I got this code from stack overflow itself and I modified to suit my needs.
Call the module TestFileOpened as below.
Sub fileCheck()
Call TestFileOpened(plannerFilePathTemp)
If fileInUse = True Then
Application.ScreenUpdating = True
Exit Sub
End If
End Sub
Here plannerFilePathTemp is the temporary file location of your original file. Whenever an excel file opened, a temp file will be created. For example, your original file location is as below
plannerFilePath = "C:\TEMP\XXX\xxx.xlsx"
Thus your temporary file location will be
plannerFilePathTemp = "C:\TEMP\XXX\~$xxx.xlsx"
or in other words, temporary file name will be ~$xxx.xlsx
The following codes will be called upon Call TestFileOpened(plannerFilePathTemp)
Public fileInUse As Boolean
Sub TestFileOpened(fileOpenedOrNot As String)
Dim Folder As String
Dim FName As String
Set objFSO = CreateObject("Scripting.FileSystemObject")
If objFSO.FileExists(fileOpenedOrNot) Then
fileInUse = True
MsgBox "Database is opened and using by " & GetFileOwner(fileOpenedOrNot) & ". Please wait a few second and click again", vbInformation, "Database in Use"
Else
fileInUse = False
End If
End Sub
Function GetFileOwner(strFileName)
Set objWMIService = GetObject("winmgmts:")
Set objFileSecuritySettings = _
objWMIService.Get("Win32_LogicalFileSecuritySetting='" & strFileName & "'")
intRetVal = objFileSecuritySettings.GetSecurityDescriptor(objSD)
If intRetVal = 0 Then
GetFileOwner = objSD.Owner.Name
Else
GetFileOwner = "Unknown"
End If
End Function
I encountered Out of memory issues also when used shared files. So during the process, I figured out the following methods to minimize memory consumption
Some tips to clear memory

File created and opened with Streamwriter vanishes when end using is hit

The following code, in a Console app
Using (System.IO.File.Create(Path & "\" & file))
End Using
Using FSW As New System.IO.StreamWriter(Path & "\" & file, False)
FSW.WriteLine(header)
creates a file and opens it to write with streamwriter. I don't think I actually need to create the file first. I think that the opening for reading would do that for me. The Console app does some stuff and then closes/disposes of the stream writer with an end using. A couple of things:
This code is being called inside a Sub that is inside a while
loop in Main.
The first time through the loop the files are created in the correct
directory. the directory to write to (path) is passed to the Sub
from the for each loop.
The paths and file names are correct: I have written them with
the immediate window and cut and pasted them into the file explorer.
They are pointing to the right place.
When the create is hit, the file appears in the directory.
When the end using is hit it vanishes. When the streamwriter object
is created the file appears in the directory. When it's end using
is hit the file vanishes.
This is exactly the opposite problem from what most people have in where the fail to .close .flush .dispose or end using a stream writer. Please also keep in mind that this code worked once. And as fore mentioned works the first time through the loop.

Access autocad object properties without opening it by VBA

I have been using folder browser for VBA, I could paste the code of it, but bottom line is that I get returned file name as a string.
Is there any way to access drawing properties (i.e number of layouts) without open?
Public Sub TestFileDialog()
dwgname = FileBrowseOpen("C:", "*", ".dwg", 1) 'dwgname is typeof string
End Sub
Its only the first step (use of FileBrowseOpen function is shown, but also i can use FolderBrowse and collect all .dwg inside of folder),actually i had in mind to batch export all layouts of selected .dwgs to currenty open one. Is there any chance for that?
To effectively read a .dwg file you'll need to open AutoCAD, otherwise the information is not accessible. Some properties may be, such as author, but not number of layouts...
But you can use AutoCAD Console (accoreconsole.exe) to run a headless AutoCAD and use APIs to read any information you need. This is really fast for reading lot's of files and the user will not see it running (but it needs to be installed anyway).
http://aucache.autodesk.com/au2012/sessionsFiles/3338/3323/handout_3338_CP3338-Handout.pdf
you could stay in VBA and use ObjectDBX
it leads to a very similar approach as accoreconsole.exe on in .NET does, i.e you won't see any drawing open in UI since it works on the database itself
It requires adding library reference (Tools->References) to "AutoCAD/ObjectDBX Common XX.Y Type Library", where "XX.Y" is "19.0" for AutoCAD 2014
a minimal functioning code is
Sub main()
Dim myAxDbDoc As AxDbDocument
Dim FullFileName As String
FullFileName = "C:\..\mydrawing.dwg" '<== put here the full name of the file to be opened
Set myAxDbDoc = AxDb_SetDrawing(FullFileName)
MsgBox myAxDbDoc.Layers.Count
End Sub
Function AxDb_SetDrawing(FullFileName As String) As AxDbDocument
Dim DBXDoc As AxDbDocument
Set DBXDoc = Application.GetInterfaceObject("ObjectDBX.AxDbDocument.19") '<== place correct AutoCAD version numeber ("19" works for AutoCAD 2014)
On Error Resume Next
DBXDoc.Open FullFileName
If Err <> 0 Then
MsgBox "Couldn't open" & vbCrLf & vbCrLf & FullFileName, vbOKOnly + vbCritical, "AxDB_SetDrawing"
Else
Set AxDb_SetDrawing = DBXDoc
End If
On Error GoTo 0
End Function
Still, you must have one AutoCAD session running from which make this sub run! But you should have it since talked about "currently open" drawing

UnauthorizedAccessException with File.AppendAllText in VB.NET

I have recently started getting System.UnauthorizedAccessException errors when using File.AppendAllText to write to a shared drive on the network. I think there were some changes to the network when this happened. The code in my application hasn't changed.
I have asked our IT dept to grant me full permission to the folder. I can see I have permissions for Modify, Read & Execute, Read, Write under my username if I navigate to the file and look at the Security tab under properties. I am also part of a group with read, write and modify permissions to the folder.
This works without error in the same folder:
File.WriteAllText(myFile, myText)
This generates a System.UnauthorizedAccessException error when it reaches the AppendallText:
If File.Exists(myFile) = False Then
' Create a file to write to.
Dim createText As String = logTime & " " & report_data
File.WriteAllText(myFile, createText)
Else
Dim appendText As String = logTime & " " & report_data
File.AppendAllText(myFile, appendText)
End If
I have tried deleting the file and creating it again, that made no difference.
I tried File.SetAttributes(myFile, FileAttributes.Normal)
The IT dept can't see what the problem is.
I can manually open, change and modify the file. The problem only arises if I am trying to do this programmatically.
Is there a different 'user' which tries to modify files? Could the file be open somehow, or would that generate a different error?
I'm using VB.NET 2012, .net framework 4.5, Windows 8.1
The network changes were the problem. It doesn't seem possible to resolve this as it is. Instead I made a copy of the text data, append my new text to that, delete the file, and save the updated text to a new file.

Moving and Deleting Files in a Loop in VB.Net

I'm trying to improve a system I have that already works. However I've ran into a problem I can't seem to find an answer to using google, perhaps I'm not searching the right questions?
I'm using a For Each loop to gather files in a directory. I then try to get each file name and some other information and determine if I should move the file temporarily or delete the file.
Example of the code used:
For Each File In Directory.GetFiles(Profile)
Dim tmpFile As System.IO.FileInfo = My.Computer.FileSystem.GetFileInfo(File) 'Never moves to the next file.
Dim Name As String = tmpFile.Name
Dim AccessDate As String = tmpFile.LastWriteTime.Date()
Dim CurrentDate As String = My.Computer.Clock.LocalTime.Date()
If AccessDate < CurrentDate Then
My.Computer.FileSystem.DeleteFile(File) 'Moves to the next file without any issues.
Threading.Thread.Sleep(150) 'If no sleep program will lock up
Else
If Not Directory.Exists(Path) Then
Directory.CreateDirectory(Path)
My.Computer.FileSystem.MoveFile(File, Path & Name)
Else
My.Computer.FileSystem.MoveFile(File, Path & Name)
End If
End If
Next
I have defined in the code what my problem is, and forgive me if there is a better way to do this, I'm self taught and still learning many things. If there's an easier way please point me in that direction.
Essentially I hit an error saying "File not found" on the move because tmpFile is not moving to the next File in the directory.