I made app to create reports and save it as .pdf At mine computer after creating report i use this code to save it as .pdf
Try
My.Computer.FileSystem.WriteAllBytes("C:\" & Form1.TextBox2.Text & "_Report.pdf", ReportViewer1.LocalReport.Render("pdf"), False)
MessageBox.Show("Exported to .pdf file on at location C:\", "Note ", MessageBoxButtons.OK, MessageBoxIcon.Information)
Catch ex As Exception
End Try
But when i send the application to someone else it won't create this the .pdf on other computer. What is required to be installed ?
On modern windows computers normal users don't have the permission to access the "C:\" directory directly. When trying to access it with your code, you get a exception, which is in your example code silently ignored.
A better way is to store the file in the users personal folder. You can use the GetFolderPath method to get it:
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
also see: http://msdn.microsoft.com/de-de/library/system.environment.specialfolder%28v=vs.110%29.aspx?cs-save-lang=1&cs-lang=vb
Related
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.
We have a Win Forms application that produces a pdf with iTextSharp, saves it to a local directory and the application then opens the file. With one customer (all XP boxes and Adobe Reader 11) it throws the following error
No application is associated with the specified file for this operation
at System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo)
at System.Diagnostics.Process.Start()
Which would suggest Adobe Reader is not associated correctly with the pdf extension apart from the fact they can navigate to the local directory and open the file without any problem whatsoever.
Anyone come across this oddity before?
Edit re ZippyV - example of a typical sub
Public Sub PDF_Functions_LogCalls_RunReport(ByVal Customer As Boolean)
Try
Dim vOutput As String = LogCalls_Run(Customer)
If Left(vOutput, 5) = "Error" Then
TaskDialog.Show(MainForm, AppBoxError("File Error", vOutput, "Error"))
Exit Sub
End If
If System.IO.File.Exists(vOutput) Then
Dim P As New Process
P.StartInfo.FileName = vOutput
P.StartInfo.Verb = "Open"
P.Start()
End If
Catch ex As Exception
EmailError(ex)
Exit Sub
End Try
End Sub
You're reading the error message wrong. I've added emphasis to the relevant part:
No application is associated with the specified file for this operation
This means that there is no application associated with the verb "Open". Change your code to simply use an empty string (or just don't set) the Verb:
P.StartInfo.FileName = vOutput
P.StartInfo.Verb = ""
P.Start()
This uses whatever the default operation is for the .pdf format, which will match the operation the user would get if they double-clicked the file in Windows Explorer.
Recent versions of Acrobat are setting the default action to "Open with Adobe Reader XI" instead of just "Open", as you can see if you right-click a .pdf file.
This is seemingly what's causing the "not associated for this operation" error.
This error actually happens when there is a difference between the default behaviour of opening the file and the relative behaviour of opening the file.
For example, if you have selected the default application to open .pdf files as Internet Explorer, and you are trying to open the same file using Process.Start() method. You will receive an exception because as per the default operations it should open that file in Internet Explorer and your application is trying to open it using Adobe reader.
To rectify this set the default application for the .pdf file as Adobe Reader and you won't receive this error any more.
I'm writing a windows service which runs as the local system account. I'm trying to make sure if I have full read/write access to a file beginning to process it any further. Here is my code:
Dim FullPath As String
FullPath = "C:\directory\file.txt"
Dim ps As Security.PermissionSet
ps = New Security.PermissionSet(Security.Permissions.PermissionState.Unrestricted)
ps.AddPermission(New Security.Permissions.FileIOPermission(Security.Permissions.FileIOPermissionAccess.AllAccess, FullPath))
ps.AddPermission(New Security.Permissions.FileIOPermission(Security.Permissions.FileIOPermissionAccess.AllAccess, IO.Path.GetDirectoryName(FullPath)))
Try
ps.Demand()
Catch ex As Security.SecurityException
System.Diagnostics.EventLog.WriteEntry("ShopLink", "File " + FullPath + " will not be parsed. " + ex.Message)
Exit Sub
Catch ex As Exception
System.Diagnostics.EventLog.WriteEntry("ShopLink", "File " + FullPath + " will not be parsed. " + ex.Message)
Exit Sub
End Try
Then I set the full access permissions for the file to "Deny" for the user account my service is running as. After executing, the code above doesn't throw any exceptions and allows file processing to begin. When the service later tries to change and/or delete the file, I get an "Access Denied" exception.
Any suggestions?
For this purpose i use thise small function:
Private Function HasAccess(ByVal ltFullPath As String)
Try
Using inputstreamreader As New StreamReader(ltFullPath)
inputstreamreader.Close()
End Using
Using inputStream As FileStream = File.Open(ltFullPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
inputStream.Close()
Return True
End Using
Catch ex As Exception
Return False
End Try
End Function
In your case then:
If HasAccess(FullPath) ...
I have solved the problem by using My.Computer.FileSystem.DeleteFile to delete the file instead of Kill. My.Computer.FileSystem.DeleteFile was executed without problems after successfully demanding full read/write access to the file in the way described above, while Kill consistently threw an "Access denied" exception.
Using "Kill"... I know this is a very old thread but I'll add this in case anyone stumbles on it like I did. I was working on some old VB6 legacy code. One of my clients users was getting a runtime exception during a file open after a kill. The code was "Killing" the file and then rebuilding it from scratch with binary data held in memory. It tuns out that the "Kill" function triggered the user's anti-virus software which locked the file long enough to cause the next "Open" statement to fail. I discovered this using an error logging utility (the name escapes me at the moment). The line in the error log file on the failed "Open" statement was that the file's status was "Delete pending" due to the user's anti-virus software.
My application can create a directory, put a file in it from a ZIP file and then remove the ZIP file.
When I then try to delete that file, I get an Access Denied error even though nothing was done with it.
Here is the code:
File.WriteAllBytes(OpslagLocatieDocumenten + myTicketNummer.ToString + "\documenten.zip", op.Documenten)
Using zp As New ZipFile(OpslagLocatieDocumenten + myTicketNummer.ToString + "\documenten.zip")
zp.FlattenFoldersOnExtract = True
zp.ExtractAll(OpslagLocatieDocumenten + myTicketNummer.ToString, ExtractExistingFileAction.OverwriteSilently)
zp.Dispose()
End Using
Try
For Each itm As String In Directory.GetFiles(OpslagLocatieDocumenten + myTicketNummer.ToString)
Try
File.Delete(itm)
Catch ex As Exception
End Try
Next
Catch ex As Exception
End Try
It looks a bit messy right now, but that is for testing purposes.
In the for-next part, right after writing the file from the ZIP, I try to delete the files.
At the moment there are two files in the directory, one ZIP and one PDF document from the ZIP.
The first file in itm is the PDF, it errors with an ACCESS DENIED.
The second file in itm is the ZIP which gets deleted.
The PDF is 311 kb in size.
Via Windows explorer I can delete it without any problem, even with the application still running.
Why is my file being locked?
What can I do to by-pass or remove this lock?
rg,
Eric
Found the problem.
The file that was added to the ZIP had it's attribute set to READ ONLY.
So when the application writes the file, windows would, as it should, not allow the application to delete it.
Unfortunately, windows does allow to delete the file via windows explorer without a message that the file is read only.
Have you also tried the File.Kill(fileLocation) method?
I am writting an ArcMap-AddIn with vb.net. I got an error when trying to compact my IWorkspace(mdb), the error is:
COMException
You tried to open a database, which was already opened by the user
'ADMIN' on Computer 'XXXXXX'. Try it again when the database is
available.
On ESRI.ArcGIS.Geodatabase.IDatabaseCompact.Compact() on
MyProject.MyClass.CompactGDB(IWorkspace pWS)
How can i compact the used workspace?
There are 8 other functions which also used my workspace.
Any suggestions?
The Code:
' CompactGDB
Public Sub CompactGDB(ByVal pWS As IWorkspace)
Dim pDatabaseCompact As IDatabaseCompact
If (TypeOf pWS Is IDatabaseCompact) Then
pDatabaseCompact = CType(pWS, IDatabaseCompact)
If (pDatabaseCompact.CanCompact) Then
Try
pDatabaseCompact.Compact()
Catch ex As Exception
MessageBox.Show(ex.type & ex.Message & ex.StackTrace, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End If
End If
End Sub
Found the solution:
Before calling the Compact() method make sure there are not any existing locks on the database.
If it is a file geodatabase then open the gdb directory in Windows Explorer and look for LOCK type files, they end in .lock.
For personal geodatabase there will be a .ldb file in the directory with the same name as the .mdb.
If you have a layer or table from the geodatabase loaded in the map
then you will not be able to remove all locks.
If another user is
accessing the geodatabase then you will not be able to remove all
locks.
If you are using arcobjects to temporarily access the
geodatabase then you need to use good practices and close any
geodatabase resources when the calling process ends. This includes
releasing all COM objects when you are finished with them.
Use the ComReleaser Class in ESRI.ArcGIS.ADF.Connection.Local namespace