Adaptive a vba excel function to be recursive - recursion

Im having trouble converting a working solution that takes a directory folder as an input and outputs the filenames and other file attributes of files container in the folder into an excel spreadsheet to a recursive solution that also outputs the files contained in subfolders. I would greatly appreciate any help!
Sub GetFileList()
Dim strFolder As String
Dim varFileList As Variant
Dim FSO As Object, myFile As Object
Dim myResults As Variant
Dim l As Long
' Get the directory from the user
With Application.FileDialog(msoFileDialogFolderPicker)
.Show
If .SelectedItems.Count = 0 Then Exit Sub
'user cancelled
strFolder = .SelectedItems(1)
End With
' Get a list of all the files in this directory. ' Note that this isn't recursive... although it could be...
varFileList = fcnGetFileList(strFolder)
If Not IsArray(varFileList) Then
MsgBox "No files found.", vbInformation
Exit Sub
End If
' Now let's get all the details for these files ' and place them into an array so it's quick to dump to XL.
ReDim myResults(0 To UBound(varFileList) + 1, 0 To 5)
' place make some headers in the array
myResults(0, 0) = "Filename"
myResults(0, 1) = "Size"
myResults(0, 2) = "Created"
myResults(0, 3) = "Modified"
myResults(0, 4) = "Accessed"
myResults(0, 5) = "Full path"
Set FSO = CreateObject("Scripting.FileSystemObject")
' Loop through our files
For l = 0 To UBound(varFileList)
Set myFile = FSO.GetFile(CStr(varFileList(l)))
myResults(l + 1, 0) = CStr(varFileList(l))
myResults(l + 1, 1) = myFile.Size
myResults(l + 1, 2) = myFile.DateCreated
myResults(l + 1, 3) = myFile.DateLastModified
myResults(l + 1, 4) = myFile.DateLastAccessed
myResults(l + 1, 5) = myFile.Path
Next l
' Dump these to a worksheet
fcnDumpToWorksheet myResults
'tidy up
Set myFile = Nothing
Set FSO = Nothing
End Sub
Private Function fcnGetFileList(ByVal strPath As String, Optional strFilter As String) As Variant ' Returns a one dimensional array with filenames ' Otherwise returns False
Dim f As String
Dim i As Integer
Dim FileList() As String
If strFilter = "" Then strFilter = "."
Select Case Right$(strPath, 1)
Case "\", "/"
strPath = Left$(strPath, Len(strPath) - 1)
End Select
ReDim Preserve FileList(0)
f = Dir$(strPath & "\" & strFilter)
Do While Len(f) > 0
ReDim Preserve FileList(i) As String
FileList(i) = f
i = i + 1
f = Dir$()
Loop
If FileList(0) <> Empty Then
fcnGetFileList = FileList
Else
fcnGetFileList = False
End If
End Function
Private Sub fcnDumpToWorksheet(varData As Variant, Optional mySh As Worksheet)
Dim iSheetsInNew As Integer
Dim sh As Worksheet, wb As Workbook
Dim myColumnHeaders() As String
Dim l As Long, NoOfRows As Long
If mySh Is Nothing Then
'make a workbook if we didn't get a worksheet
iSheetsInNew = Application.SheetsInNewWorkbook
Application.SheetsInNewWorkbook = 1
Set wb = Application.Workbooks.Add
Application.SheetsInNewWorkbook = iSheetsInNew
Set sh = wb.Sheets(1)
Else
Set mySh = sh
End If
With sh
Range(.Cells(1, 1), .Cells(UBound(varData, 1) + 1, UBound(varData, 2) + 1)) = varData
.UsedRange.Columns.AutoFit
End With
Set sh = Nothing
Set wb = Nothing
End Sub

I've rewritten the code to pass your results array and a counter to the recursive function. The function fills the array and calls itself with any subfolders
Sub GetFileList()
Dim strFolder As String
Dim FSO As Object
Dim fsoFolder As Object
Dim myResults As Variant
Dim lCount As Long
Set FSO = CreateObject("Scripting.FileSystemObject")
' Get the directory from the user
With Application.FileDialog(msoFileDialogFolderPicker)
.Show
If .SelectedItems.Count = 0 Then Exit Sub
'user cancelled
strFolder = .SelectedItems(1)
End With
Set fsoFolder = FSO.GetFolder(strFolder)
'the variable dimension has to be the second one
ReDim myResults(0 To 5, 0 To 0)
' place make some headers in the array
myResults(0, 0) = "Filename"
myResults(1, 0) = "Size"
myResults(2, 0) = "Created"
myResults(3, 0) = "Modified"
myResults(4, 0) = "Accessed"
myResults(5, 0) = "Full path"
'Send the folder to the recursive function
FillFileList fsoFolder, myResults, lCount
' Dump these to a worksheet
fcnDumpToWorksheet myResults
'tidy up
Set FSO = Nothing
End Sub
Private Sub FillFileList(fsoFolder As Object, ByRef myResults As Variant, ByRef lCount As Long, Optional strFilter As String)
Dim i As Integer
Dim fsoFile As Object
Dim fsoSubFolder As Object
Dim fsoSubFolders As Object
'load the array with all the files
For Each fsoFile In fsoFolder.Files
lCount = lCount + 1
ReDim Preserve myResults(0 To 5, 0 To lCount)
myResults(0, lCount) = fsoFile.Name
myResults(1, lCount) = fsoFile.Size
myResults(2, lCount) = fsoFile.DateCreated
myResults(3, lCount) = fsoFile.DateLastModified
myResults(4, lCount) = fsoFile.DateLastAccessed
myResults(5, lCount) = fsoFile.Path
Next fsoFile
'recursively call this function with any subfolders
Set fsoSubFolders = fsoFolder.SubFolders
For Each fsoSubFolder In fsoSubFolders
FillFileList fsoSubFolder, myResults, lCount
Next fsoSubFolder
End Sub
Private Sub fcnDumpToWorksheet(varData As Variant, Optional mySh As Worksheet)
Dim iSheetsInNew As Integer
Dim sh As Worksheet, wb As Workbook
Dim myColumnHeaders() As String
Dim l As Long, NoOfRows As Long
If mySh Is Nothing Then
'make a workbook if we didn't get a worksheet
iSheetsInNew = Application.SheetsInNewWorkbook
Application.SheetsInNewWorkbook = 1
Set wb = Application.Workbooks.Add
Application.SheetsInNewWorkbook = iSheetsInNew
Set sh = wb.Sheets(1)
Else
Set mySh = sh
End If
'since we switched the array dimensions, have to transpose
With sh
Range(.Cells(1, 1), .Cells(UBound(varData, 2) + 1, UBound(varData, 1) + 1)) = _
Application.WorksheetFunction.Transpose(varData)
.UsedRange.Columns.AutoFit
End With
Set sh = Nothing
Set wb = Nothing
End Sub

Related

how to move file another folder using asp

how to move existing file to another folder using asp, but i will send file series "scn_1" only
FROM -- > d:\image\scn_1_1.jpg , d:]image\scn_1_2.jpg
TO --> d:\image2\backup\scn_1_1.jpg, scn_1_2.jpg
in asp or vb
this is my sample code
Dim fs
fs = Server.CreateObject("Scripting.FileSystemObject")
Dim scanpath = Request.QueryString("spath")
Dim rkpath = Request.QueryString("rkpath")
Dim series = Request.QueryString("series")
fs.MoveFile("D:\Ethiraj\ScanDcocument\scanimage\test.txt", "D:\Ethiraj\ScanDcocument\Rk_Images\test.txt")
fs = Nothing
Dim fs fs = Server.CreateObject("Scripting.FileSystemObject") Dim scanpath = Request.QueryString("virtu_dir") Dim rkpath = Request.QueryString("RK_path") Dim series = Request.QueryString("series") Dim fileToFind = series & "*.jpg" Dim dirs As String() = IO.Directory.GetFiles(scanpath, fileToFind) Dim dir As String For Each dir In dirs If dir.Contains(series) Then Dim filename = System.IO.Path.GetFileName(dir) fs.CopyFile(dir, rkpath + "\" + filename) fs = Nothing End If Next

Initiating an Dynamic Multidimensional Array in VB.net

I am receiving a "Object reference not set to an instance of an object." Error when trying to populate the fileDetails array. I am new to vb.net and I am lost.
Public Sub FindAllOrphanFiles(ByVal targetDirectory As String)
Dim fileEntries As String() = Directory.GetFiles(targetDirectory)
' Process the list of files found in the directory.
Dim files As String
Dim iCount As Integer = 0
Dim fileDetails As String(,)
For Each files In fileEntries
Dim fileIcon As String
Dim thisFile As New IO.FileInfo(files)
Dim fileName As String = thisFile.Name
Dim fileSize As String = thisFile.Length
Dim fileDateModified As String = thisFile.LastWriteTime
Dim fileExtension As String = Path.GetExtension(fileName)
Dim fileShortPath As String = Replace(Replace(files, uploadFolderPath, ""), fileName, "")
Dim fileFullPath As String = files
If fileExtension = ".pdf" Then
fileIcon = "acrobat"
Else
fileIcon = "paint"
End If
' Write to Array
fileDetails(iCount, 0) = fileIcon
fileDetails(iCount, 1) = fileName
fileDetails(iCount, 2) = fileShortPath
fileDetails(iCount, 3) = fileDateModified
fileDetails(iCount, 4) = fileSize
fileDetails(iCount, 5) = fileFullPath
iCount += 1
Next files
Dim subdirectoryEntries As String() = Directory.GetDirectories(targetDirectory)
' Recurse into subdirectories of this directory.
Dim subdirectory As String
For Each subdirectory In subdirectoryEntries
FindAllOrphanFiles(subdirectory)
Next subdirectory
End Sub 'FindAllOrphanFiles
Any help would be greatly appreciated.
Your array is not initialized. If you know the size at some point before your loop, you should initialize it using REDIM:
Dim fileDetails As String(,)
redim fileDetails(fileEntries.Count -1,5)
For Each files In fileEntries
....
If you don't know it ahead of time, use Redim Preserve inside you loop:
Dim fileDetails As String(,)
Dim I as int32 = -1
For Each files In fileEntries
I += 1
redim preserve fileDetails(i,5)
....

Upload files creating dynamic folder based on the user input in asp

Here is my code that uploads a file to a folder...but I need to upload a file to a folder which might not exist yet. How can i create a folder before uploading the file or is there a parameter in asp that creates a folder before copying the file there if it doesn't exit?..i need to create folder based on the user input...
<%
Class FileUploader
Public Files
Private mcolFormElem
Private Sub Class_Initialize()
Set Files = Server.CreateObject("Scripting.Dictionary")
Set mcolFormElem = Server.CreateObject("Scripting.Dictionary")
End Sub
Private Sub Class_Terminate()
If IsObject(Files) Then
Files.RemoveAll()
Set Files = Nothing
End If
If IsObject(mcolFormElem) Then
mcolFormElem.RemoveAll()
Set mcolFormElem = Nothing
End If
End Sub
Public Property Get Form(sIndex)
Form = ""
If mcolFormElem.Exists(LCase(sIndex)) Then Form = mcolFormElem.Item(LCase(sIndex))
End Property
Public Default Sub Upload()
Dim biData, sInputName
Dim nPosBegin, nPosEnd, nPos, vDataBounds, nDataBoundPos
Dim nPosFile, nPosBound
biData = Request.BinaryRead(Request.TotalBytes)
nPosBegin = 1
nPosEnd = InstrB(nPosBegin, biData, CByteString(Chr(13)))
If (nPosEnd-nPosBegin) <= 0 Then Exit Sub
vDataBounds = MidB(biData, nPosBegin, nPosEnd-nPosBegin)
nDataBoundPos = InstrB(1, biData, vDataBounds)
Do Until nDataBoundPos = InstrB(biData, vDataBounds & CByteString("--"))
nPos = InstrB(nDataBoundPos, biData, CByteString("Content-Disposition"))
nPos = InstrB(nPos, biData, CByteString("name="))
nPosBegin = nPos + 6
nPosEnd = InstrB(nPosBegin, biData, CByteString(Chr(34)))
sInputName = CWideString(MidB(biData, nPosBegin, nPosEnd-nPosBegin))
nPosFile = InstrB(nDataBoundPos, biData, CByteString("filename="))
nPosBound = InstrB(nPosEnd, biData, vDataBounds)
If nPosFile <> 0 And nPosFile < nPosBound Then
Dim oUploadFile, sFileName
Set oUploadFile = New UploadedFile
nPosBegin = nPosFile + 10
nPosEnd = InstrB(nPosBegin, biData, CByteString(Chr(34)))
sFileName = CWideString(MidB(biData, nPosBegin, nPosEnd-nPosBegin))
oUploadFile.FileName = Right(sFileName, Len(sFileName)-InStrRev(sFileName, "\"))
nPos = InstrB(nPosEnd, biData, CByteString("Content-Type:"))
nPosBegin = nPos + 14
nPosEnd = InstrB(nPosBegin, biData, CByteString(Chr(13)))
oUploadFile.ContentType = CWideString(MidB(biData, nPosBegin, nPosEnd-nPosBegin))
nPosBegin = nPosEnd+4
nPosEnd = InstrB(nPosBegin, biData, vDataBounds) - 2
oUploadFile.FileData = MidB(biData, nPosBegin, nPosEnd-nPosBegin)
If oUploadFile.FileSize > 0 Then Files.Add LCase(sInputName), oUploadFile
Else
nPos = InstrB(nPos, biData, CByteString(Chr(13)))
nPosBegin = nPos + 4
nPosEnd = InstrB(nPosBegin, biData, vDataBounds) - 2
If Not mcolFormElem.Exists(LCase(sInputName)) Then mcolFormElem.Add LCase(sInputName), CWideString(MidB(biData, nPosBegin, nPosEnd-nPosBegin))
End If
nDataBoundPos = InstrB(nDataBoundPos + LenB(vDataBounds), biData, vDataBounds)
Loop
End Sub
'String to byte string conversion
Private Function CByteString(sString)
Dim nIndex
For nIndex = 1 to Len(sString)
CByteString = CByteString & ChrB(AscB(Mid(sString,nIndex,1)))
Next
End Function
'Byte string to string conversion
Private Function CWideString(bsString)
Dim nIndex
CWideString =""
For nIndex = 1 to LenB(bsString)
CWideString = CWideString & Chr(AscB(MidB(bsString,nIndex,1)))
Next
End Function
End Class
Class UploadedFile
Public ContentType
Public FileName
Public FileData
Public Property Get FileSize()
FileSize = LenB(FileData)
End Property
Public Sub SaveToDisk(sPath)
Dim oFS, oFile
Dim nIndex
If sPath = "" Or FileName = "" Then Exit Sub
If Mid(sPath, Len(sPath)) <> "\" Then sPath = sPath & "\"
Set oFS = Server.CreateObject("Scripting.FileSystemObject")
If Not oFS.FolderExists(sPath) Then Exit Sub
Set oFile = oFS.CreateTextFile(sPath & FileName, True)
For nIndex = 1 to LenB(FileData)
oFile.Write Chr(AscB(MidB(FileData,nIndex,1)))
Next
oFile.Close
End Sub
Public Sub SaveToDatabase(ByRef oField)
If LenB(FileData) = 0 Then Exit Sub
If IsObject(oField) Then
oField.AppendChunk FileData
End If
End Sub
End Class
%>
can anybody help me?
i need to upload the set of documents corresponding to that proforma number...so i need to create a folder in the name of proforma number which is entered by the user...
just use the filesystemobject to create a directory like so:
dim fso : set fso = server.createobject("scripting.filesystemobject")
dim absolutePath : absolutePath = "d:\path\to\new\directory"
if not fso.FolderExists(absolutePath) then
fso.createFolder( absolutePath )
end if
set fso = nothing
check the api doc for fso
to use that "proforma" number just get it from request.form("name_for_proforma_field")...
as you are using the upload class you have to use
fileUploader.Form("name_for_proforma_field")
instead of
request.form
because after using request.binaryread you do not have access to the request.forms collection...
brief example (not tested):
dim upl : set upl = new FileUploader()
upl.upload()
' from now on you have to use upl.Form() instad of request.form
dim folderName : folderName = upl.Form("name_for_proforma_field")
dim fso : set fso = server.createobject("scripting.filesystemobject")
dim absolutePath : absolutePath = "d:\path\to\new\directory\" & folderName
if not fso.FolderExists(absolutePath) then
fso.createFolder( absolutePath )
end if
set fso = nothing
for further information about the fileupload class have a look here

counting shopping cart 2d Array items in asp-classic

I have a shopping cart that using 2d array Cart(3, 20) to store user shop in a session.
It storing data like this:
Cart(0,0) = Product_ID
Cart(1,0) = Product_Name
Cart(2,0) = Product_Price
Cart(3,0) = Product_Qty
I want to count Items based on product_id ( we have not repetitive product_id)
I found a function here:
Function UniqueEntryCount(SourceRange)
Dim MyDataset
Dim dic
Set dic=Server.CreateObject("Scripting.Dictionary")
MyDataset = SourceRange
For i = 1 To UBound(MyDataset, 2)
if not dic.Exists(MyDataset(0, i)) then dic.Add MyDataset(0, i), ""
Next
UniqueEntryCount = dic.Count
Set dic = Nothing
End Function
But one problem is remain, When my Cart is empty, it show me 1
How can solved it?
An unitialized fixed array (Dim a(i, j)) contains i * j empty elements; your
if not dic.Exists(MyDataset(0, i)) then dic.Add MyDataset(0, i), ""
will pick up and count the first empty item. Demonstrated in code:
Dim afCart(3, 4)
Dim dicPID : Set dicPID = countPID00(afCart)
Dim aKeys : aKeys = dicPID.Keys
Dim vKey : vKey = aKeys(0)
WScript.Echo "A", dicPID.Count, TypeName(vKey)
Set dicPID = countPID(afCart)
WScript.Echo "B", dicPID.Count
afCart(0, 0) = "ignored"
afCart(0, 1) = 4711
afCart(0, 2) = 4712
afCart(0, 3) = 4711
' afCart(0, 4) = "not initialized/Empty"
Set dicPID = countPID(afCart)
WScript.Echo "C"
For Each vKey In dicPID.Keys
WScript.Echo "", vKey, "=", dicPID(vKey)
Next
Function countPID00(afCart)
Dim dicRVal : Set dicRVal = CreateObject("Scripting.Dictionary")
Dim MyDataset : MyDataset = afCart ' waste of ressources
Dim iRow
For iRow = 1 To UBound(MyDataset, 2)
If Not dicRVal.Exists(MyDataset(0, iRow)) Then
dicRVal(MyDataset(0, iRow)) = "" ' loss of info; will pick up Empty item
End If
Next
Set countPID00 = dicRVal
End Function ' countPID00
Function countPID(afCart)
Dim dicRVal : Set dicRVal = CreateObject("Scripting.Dictionary")
Dim iRow
For iRow = 1 To UBound(afCart, 2)
If Not IsEmpty(afCart(0, iRow)) Then
dicRVal(afCart(0, iRow)) = dicRVal(afCart(0, iRow)) + 1
End If
Next
Set countPID = dicRVal
End Function ' countPID
output:
A 1 Empty
B 0
C
4711 = 2
4712 = 1

delaying file read/write till it's done being used?

I have a vb.net MVC3 Razor app that generates PDF files. The problem is that if 2 seperate users click the print button at the same time it throws the following exception..:
The process cannot access the file 'E:\web\xxxxxxxxxxsonl\PDF_Files\MailingLables.pdf' because it is being used by another process.
All of the controller actions to do with printing are basically like below:
Function Ind_Cert(ByVal firstName As String, ByVal lastname As String, ByVal classRef As String)
Dim _Attendance As attendance = db.attendances.Where(Function(f) f.Completed_Class = "Completed" And f.firstName = firstName And f.lastName = lastname).FirstOrDefault
If Not IsNothing(_Attendance) Then
Dim _reg_classes As List(Of reg_classes) = db.reg_classes.ToList
Dim _registrants As List(Of reg_info) = db.reg_info.ToList
Dim _courses As List(Of cours) = db.courses.ToList
Dim _Board As List(Of board_members) = db.board_members.ToList
Dim Board_Member As board_members = _Board.Where(Function(f) f.Official_Cap = "xxxxxx President").FirstOrDefault
Dim RecordId As Integer = 0
Dim conf_info As conf_info = db.conf_info.Single(Function(r) r.id = 0)
Dim conf_num As Integer = conf_info.conf_number
Dim _conf_num As String = conf_num.ToString
Dim Length As Integer
Dim _prefix As String = String.Empty
If Str(conf_num) <> "" Then
Length = Str(conf_num).Length
End If
Dim Divisor As Integer = 10 ^ (Length - 1)
Dim conf_num_start As Integer = 0
Dim Digits(Length - 1) As Integer
While (conf_num > 10)
'Extract the first digit
Digits(conf_num_start) = Int(conf_num / Divisor)
'Extract remainder number - and store it back in Num
conf_num = conf_num Mod Divisor
'Decrease Divisor's value by 1/10th units
Divisor /= 10
'Increment Index
conf_num_start += 1
End While
If conf_num = 0 Or 4 Or 5 Or 6 Or 7 Or 8 Or 9 Then _prefix = "th"
If conf_num = 1 Then _prefix = "st"
If conf_num = 2 Then _prefix = "nd"
If conf_num = 3 Then _prefix = "rd"
Dim pdfpath As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\PDF_Files\"
Dim imagepath As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\PDF_Files\"
Dim _PdfName As String = "Cert_" + lastname + ".pdf"
Dim doc As New Document
doc.SetPageSize(iTextSharp.text.PageSize.LETTER.Rotate())
doc.SetMargins(1, 1, 1, 1)
Dim _pageCounter As Integer = 0
Dim Californian As BaseFont = BaseFont.CreateFont(Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\Fonts\" + "CALIFB.TTF", BaseFont.CP1252, BaseFont.EMBEDDED)
Dim Copper As BaseFont = BaseFont.CreateFont(Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\Fonts\" + "COPRGTB.TTF", BaseFont.CP1252, BaseFont.EMBEDDED)
Dim Bold_Times As BaseFont = BaseFont.CreateFont(BaseFont.TIMES_BOLD, BaseFont.CP1252, False)
Dim BF_Times As BaseFont = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, False)
Dim F_Name As New Font(BF_Times, 16, Font.BOLD, BaseColor.BLACK)
Dim _Parking_Name As New Font(BF_Times, 18, Font.NORMAL, BaseColor.BLACK)
Dim _Parking_Date As New Font(BF_Times, 24, Font.BOLD, BaseColor.BLACK)
'**********************************Y lines for trial***********************************
Dim y_line1 As Integer = 670
Dim _Counter As Integer = 1
Dim _Page As String = 1
Dim _CertJpg As Image = Image.GetInstance(imagepath + "/cert.jpg")
Dim imageWidth As Decimal = _CertJpg.Width
Dim imageHeight As Decimal = _CertJpg.Height
Dim writer As PdfWriter = PdfWriter.GetInstance(doc, New FileStream(pdfpath + _PdfName, FileMode.Create))
doc.Open()
Dim cb As PdfContentByte = writer.DirectContent
If _Attendance.Completed_Class = "Completed" Then
Dim _confInfo As conf_info = db.conf_info.Single(Function(a) a.id = 0)
Dim year As String = Right(_confInfo.conf_start_date, 4)
Dim _reg As reg_info = db.reg_info.Single(Function(b) b.id = _Attendance.reg_id)
Dim name As String = _reg.first_name + " " + _reg.last_name
Dim _dates As String = _confInfo.conf_start_date + " - " + _confInfo.conf_end_date
Dim _course As cours = db.courses.Single(Function(c) c.course_ref = _Attendance.course_ref)
Dim _className As String = _course.course_title.ToString
Dim _hours As String = _course.course_hours
Dim _certName As String = Board_Member.First_Name + " " + Board_Member.last_name
_CertJpg.Alignment = iTextSharp.text.Image.UNDERLYING
_CertJpg.ScaleToFit(792, 611)
doc.Add(_CertJpg)
cb.BeginText()
cb.SetFontAndSize(Californian, 36)
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "CERTIFICATE OF COMPLETION", 396, 397.91, 0)
cb.SetFontAndSize(Bold_Times, 22)
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, name, 396, 322.35, 0)
cb.SetFontAndSize(Bold_Times, 16)
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, _hours + " Hours", 297.05, 285.44, 0)
cb.SetFontAndSize(Bold_Times, 16)
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, _dates, 494.95, 285.44, 0)
cb.SetFontAndSize(Bold_Times, 16)
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "Class Attended: " + " " + _Attendance.course_ref + " -- " + _className, 396, 230.34, 0)
cb.SetFontAndSize(Copper, 16)
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, _conf_num + _prefix + " Annual Conference " + _dates, 396, 193.89, 0)
cb.SetFontAndSize(Bold_Times, 13)
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, _certName, 396, 175.69, 0)
cb.SetFontAndSize(Bold_Times, 10)
cb.ShowTextAligned(PdfContentByte.ALIGN_CENTER, "xxxxxxx President", 396, 162.64, 0)
cb.EndText()
End If
doc.Close()
Return _PdfName
Else
Return "Fail"
End If
End Function
This error happens like I said any time 2 users try to generate a PDF file at the same time. Anyone know of a fix for this issue? Google has turned up countless pages about someone can't delete a file in windows because its being used. But that isn't much help.. Any ideas???
You can pretty much do two things.
Add a lock on the file and block the second (and third and fourth, etc) until the lock is cleared
Create a unique file for each instance.
I'd recommend #2. You can keep the same file name, just put the file in a unique directory. A GUID is usually the easiest for me:
Dim pdfpath As String = Path.Combine(AppDomain.CurrentDomain.BaseDirectory) + "\PDF_Files\"
pdfPath = Path.Combine(pdfPath, Guid.NewGuid.ToString())
Directory.CreateDirectory(pdfPath)
Then change your return to include the path created above.
Can you create the PDF file with a random file name to avoid the conflict in the first place?
Wrap your file access code in a lock.
lock (this)
{
//Write file
}
See Lock on MSDN

Resources