Save file if error reading with Stream Reader - vb.net

I am trying to parse a uploaded txt file. I need to save the file if there is an error parsing it. The problem is that the parser is using a Stream Reader and if an error occurs it just saves the empty file and not the file contents.
Dim file As HttpPostedFile = context.Request.Files(0)
If Not IsNothing(file) AndAlso file.ContentLength > 0 AndAlso Path.GetExtension(file.FileName) = ".txt" Then
Dim id As Integer = (Int32.Parse(context.Request("id")))
Try
ParseFile(file, id)
context.Response.Write("success")
Catch ex As Exception
Dim filename As String = file.FileName
Dim uploadPath = context.Server.MapPath("~/Errors/MyStudentDataFiles/")
file.SaveAs(uploadPath + id.ToString() + filename)
End Try
Else
context.Response.Write("error")
End If
My ParseFile method is something like this
Protected Sub ParseFile(ByVal studentLoanfile As HttpPostedFile, ByVal id As Integer)
Using r As New StreamReader(studentLoanfile.InputStream)
line = GetLine(r)
End Using
End Sub
Is there a way to Clone the file before it gets passed into the parseFile sub or a way to read the file without loosing the contents?
Thanks in advance

For anyone who runs into this problem in the future, I ended up reading the file to the end and saving it into a variable. Then converted it back into a memory stream to use for the parser. If an error occurs, I just create a new file with the string. This is the code I used.
Dim id As Integer = (Int32.Parse(context.Request("id")))
'Read full file for error logging
Dim content As String = [String].Empty
Using sr = New StreamReader(uploadedFile.InputStream)
content = sr.ReadToEnd()
End Using
'Convert it back into a stream
Dim byteArray As Byte() = Encoding.UTF8.GetBytes(content)
Dim stream As New MemoryStream(byteArray)
Try
ParseFile(stream, id, content)
context.Response.Write("success")
Catch ex As Exception
Dim filename As String = uploadedFile.FileName
Dim uploadPath = context.Server.MapPath("~/Errors/MyStudentDataFiles/")
'Save full file on error
Using sw As StreamWriter = File.CreateText(uploadPath + id.ToString() + filename)
sw.WriteLine(content)
End Using
context.Response.Write("error")
Throw ex
End Try
Else
context.Response.Write("error")
End If

Related

how to use ZoomNet DownloadFileAsync

I'm using a Nuget package Jericho /ZoomNet, trying to download a zoom recording (mp4) [winform App]
I'm not sure how the DownloadFileAsync() works to save the File from the Stream, I keep getting task cancelled exception
Can you point to any similar examples ?
UPDATE
So i talked to the Author of the package,
he made a beta release to download large files more efficiently, and also showed me you can add your own client object to control the timeout according to file size, also using the ConfigureAwait(False) was necessary.
Dim myHttpClient = New HttpClient() With {
.Timeout = TimeSpan.FromMinutes(10) }
Dim azoomClient = New ZoomClient(connectionInfo,
myHttpClient)
Dim sourceStream = Await
azoomClient.CloudRecordings.DownloadFileAsync(fdownloadFileName, ct).ConfigureAwait(False)
Using outStream = File.OpenWrite(DestFileName)
sourceStream.CopyTo(outStream)
End Using
This is the code I've tried
Private azoomClient = New ZoomClient(connectionInfo)
Dim fdownloadFileName As String = "c:\zoomrec1.mp4"
Dim ct As New Threading.CancellationToken
Dim sourceStream As Stream
sourceStream = Await azoomClient.CloudRecordings.DownloadFileAsync(fdownloadFileName, ct).ConfigureAwait(False)
DumpStream(sourceStream, DestFileName)
Private Async Function DumpStream(ByVal outStream As Stream, ByVal outputFileName As String) As Task
Try
' Dump the contents of a stream to a file
outStream.Flush()
Dim SavePos As Long = outStream.Position ' Save the original position in the stream
outStream.Seek(0, SeekOrigin.Begin)
Dim f As Stream = File.OpenWrite(outputFileName)
CopyStream(outStream, f)
outStream.Position = SavePos ' Go back to the original postion in the stream
f.Close()
Catch ex As Exception
MessageBox.Show("Error:DumpStream()>" & ex.Message)
End Try
End Function
Public Shared Sub CopyStream(ByVal input As Stream, ByVal output As Stream)
Try
' Copy the contents of one stream to another stream
Dim buf As Byte() = New Byte(8 * 1024 - 1) {} ' A buffer for storing data while copying
Dim len As Integer
len = input.Read(buf, 0, buf.Length)
While len > 0
output.Write(buf, 0, len)
len = input.Read(buf, 0, buf.Length)
End While
Catch ex As Exception
MessageBox.Show("Error:CopyStream()>" & ex.Message)
End Try
End Sub
'''
i can get the download url filename with this call,
'''
Dim apiKey = "abc" Dim apiSecret = "123"
Dim connectionInfo As New JwtConnectionInfo(apiKey, apiSecret)
Dim v As Object = azoomClient.CloudRecordings.GetRecordingInformationAsync(MeetingID)
Dim modelsRecording = Await v
downloadFileName = CStr(modelsRecording.RecordingFiles.Where(Function(z)
z.FileType = Models.RecordingFileType.Video)(0).DownloadUrl)
'''
I updated the code above with a working solution.

Google Drive API v3 VB.NET Upload To Spesific Folder

Please Help, i'm trying to upload file to specific folder in my google drive using Vb.net. but, i'm googling for hours and not get working code. i cant sleep because this. here is my code:
Private Sub UploadFile(FilePath As String)
Try
If Service.ApplicationName <> "Google Drive VB Dot Net" Then CreateService()
Dim TheFile As New File()
TheFile.Name = "Database Sekretariat.accdb"
TheFile.Description = "A test document"
'TheFile.MimeType = "text/plain"
TheFile.Parents(0) = "1uMeTMRtvhm5_98udPmV8kp19aGtrmeQj"
Dim ByteArray As Byte() = System.IO.File.ReadAllBytes(FilePath)
Dim Stream As New System.IO.MemoryStream(ByteArray)
Dim UploadRequest As FilesResource.CreateMediaUpload = Service.Files.Create(TheFile, Stream, TheFile.MimeType)
UploadRequest.Upload()
Dim file As File = UploadRequest.ResponseBody
MsgBox("Upload Selesai " & file.Name & "")
Catch ex As Exception
MsgBox("Upload Gagal")
End Try
End Sub
use it in the following way, it is functional
First, i look for the ID folder
Public Sub SearchFolder()
IDFolderSave = String.Empty 'Global Variable
Try
Dim findrequest As FilesResource.ListRequest = Service.Files.List
Dim listFolder As Data.FileList = findrequest.Execute
For Each item As File In listFolder.Files
If item.MimeType = "application/vnd.google-apps.folder" Then
If item.Name = "NameFolder" Then
IDFolderSave = item.Id.ToString
Exit For
End If
End If
Next
Catch ex As Exception
Throw ex
End Try
'MsgBox("Folder id: " + idFolder)
End Sub
Second, upload file
Public Sub UploadFileInFolder()
Dim FilePath As String = String.Empty
FilePath = "C:\Icons\Loadding.gif"
Dim plist As List(Of String) = New List(Of String)
SearchFolder()
plist.Add(IDFolderSave) 'Set parent folder
If (System.IO.File.Exists(FilePath)) Then
Dim fileMetadata = New File() With {
.Name = "Test",
.Parents = plist
}
Dim request As FilesResource.CreateMediaUpload
Using stream = New System.IO.FileStream(FilePath, System.IO.FileMode.Open)
request = Service.Files.Create(fileMetadata, stream, "application/octet-stream")
request.Fields = "id, parents"
request.Upload()
End Using
Dim file As File = request.ResponseBody
IDFileShared = file.Id
SharedFile()
MsgBox("File upload: " + file.Id)
Else
MsgBox("File does not exist: " + FilePath)
End If
End Sub
I hope it helps you

VB.Net Merge multiple pdfs into one and export

I have to merge multiple PDFs into a single PDF.
I am using the iText.sharp library, and collect converted the code and tried to use it (from here)
The actual code is in C# and I converted that to VB.NET.
Private Function MergeFiles(ByVal sourceFiles As List(Of Byte())) As Byte()
Dim mergedPdf As Byte() = Nothing
Using ms As New MemoryStream()
Using document As New Document()
Using copy As New PdfCopy(document, ms)
document.Open()
For i As Integer = 0 To sourceFiles.Count - 1
Dim reader As New PdfReader(sourceFiles(i))
' loop over the pages in that document
Dim n As Integer = reader.NumberOfPages
Dim page As Integer = 0
While page < n
page = page + 1
copy.AddPage(copy.GetImportedPage(reader, page))
End While
Next
End Using
End Using
mergedPdf = ms.ToArray()
End Using
End Function
I am now getting the following error:
An item with the same key has already been added.
I did some debugging and have tracked the problem down to the following lines:
copy.AddPage(copy.GetImportedPage(reader,
copy.AddPage(copy.GetImportedPage(reader, page)))
Why is this error happening?
I have a console that monitors individual folders in a designated folder then needs to merge all of the pdf's in that folder into a single pdf. I pass an array of file paths as strings and the output file i would like.
This is the function i use.
Public Shared Function MergePdfFiles(ByVal pdfFiles() As String, ByVal outputPath As String) As Boolean
Dim result As Boolean = False
Dim pdfCount As Integer = 0 'total input pdf file count
Dim f As Integer = 0 'pointer to current input pdf file
Dim fileName As String
Dim reader As iTextSharp.text.pdf.PdfReader = Nothing
Dim pageCount As Integer = 0
Dim pdfDoc As iTextSharp.text.Document = Nothing 'the output pdf document
Dim writer As PdfWriter = Nothing
Dim cb As PdfContentByte = Nothing
Dim page As PdfImportedPage = Nothing
Dim rotation As Integer = 0
Try
pdfCount = pdfFiles.Length
If pdfCount > 1 Then
'Open the 1st item in the array PDFFiles
fileName = pdfFiles(f)
reader = New iTextSharp.text.pdf.PdfReader(fileName)
'Get page count
pageCount = reader.NumberOfPages
pdfDoc = New iTextSharp.text.Document(reader.GetPageSizeWithRotation(1), 18, 18, 18, 18)
writer = PdfWriter.GetInstance(pdfDoc, New FileStream(outputPath, FileMode.OpenOrCreate))
With pdfDoc
.Open()
End With
'Instantiate a PdfContentByte object
cb = writer.DirectContent
'Now loop thru the input pdfs
While f < pdfCount
'Declare a page counter variable
Dim i As Integer = 0
'Loop thru the current input pdf's pages starting at page 1
While i < pageCount
i += 1
'Get the input page size
pdfDoc.SetPageSize(reader.GetPageSizeWithRotation(i))
'Create a new page on the output document
pdfDoc.NewPage()
'If it is the 1st page, we add bookmarks to the page
'Now we get the imported page
page = writer.GetImportedPage(reader, i)
'Read the imported page's rotation
rotation = reader.GetPageRotation(i)
'Then add the imported page to the PdfContentByte object as a template based on the page's rotation
If rotation = 90 Then
cb.AddTemplate(page, 0, -1.0F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(i).Height)
ElseIf rotation = 270 Then
cb.AddTemplate(page, 0, 1.0F, -1.0F, 0, reader.GetPageSizeWithRotation(i).Width + 60, -30)
Else
cb.AddTemplate(page, 1.0F, 0, 0, 1.0F, 0, 0)
End If
End While
'Increment f and read the next input pdf file
f += 1
If f < pdfCount Then
fileName = pdfFiles(f)
reader = New iTextSharp.text.pdf.PdfReader(fileName)
pageCount = reader.NumberOfPages
End If
End While
'When all done, we close the document so that the pdfwriter object can write it to the output file
pdfDoc.Close()
result = True
End If
Catch ex As Exception
Return False
End Try
Return result
End Function
the code that was marked correct does not close all the file streams therefore the files stay open within the app and you wont be able to delete unused PDFs within your project
This is a better solution:
Public Sub MergePDFFiles(ByVal outPutPDF As String)
Dim StartPath As String = FileArray(0) ' this is a List Array declared Globally
Dim document = New Document()
Dim outFile = Path.Combine(outPutPDF)' The outPutPDF varable is passed from another sub this is the output path
Dim writer = New PdfCopy(document, New FileStream(outFile, FileMode.Create))
Try
document.Open()
For Each fileName As String In FileArray
Dim reader = New PdfReader(Path.Combine(StartPath, fileName))
For i As Integer = 1 To reader.NumberOfPages
Dim page = writer.GetImportedPage(reader, i)
writer.AddPage(page)
Next i
reader.Close()
Next
writer.Close()
document.Close()
Catch ex As Exception
'catch a Exception if needed
Finally
writer.Close()
document.Close()
End Try
End Sub
I realize I'm pretty late to the party, but after reading the comments from #BrunoLowagie, I wanted to see if I could put something together myself that uses the examples from his linked sample chapter. It's probably overkill, but I put together some code that merges multiple PDFs into a single file that I posted on the Code Review SE site (the post, VB.NET - Error Handling in Generic Class for PDF Merge, contains the full class code). It only merges PDF files right now, but I'm planning on adding methods for additional functionality later.
The "master" method (towards the end of the Class block in the linked post, and also posted below for reference) handles the actual merging of the PDF files, but the multiple overloads provide a number of options for how to define the list of original files. So far, I've included the following features:
The methods return a System.IO.FileInfo object if the merge is successful.
Provide a System.IO.DirectoryInfo object or a System.String identifying a path and it will collect all PDF files in that directory (including sub-directories if specified) to merge.
Provide a List(Of System.String) or a List(Of System.IO.FileInfo) specifying the PDFs you want to merge.
Identify how the PDFs should be sorted before the merge (especially useful if you use one of the MergeAll methods to get all PDF files in a directory).
If the specified output PDF file already exists, you can specify whether or not you want to overwrite it. (I'm considering adding the "ability" to automatically adjust the output PDF file's name if it already exists).
Warning and Error properties provide a way to get feedback in the calling method, whether or not the merge is successful.
Once the code is in place, it can be used like this:
Dim PDFDir As New IO.DirectoryInfo("C:\Test Data\PDF\")
Dim ResultFile As IO.FileInfo = Nothing
Dim Merger As New PDFManipulator
ResultFile = Merger.MergeAll(PDFDir, "C:\Test Data\PDF\Merged.pdf", True, PDFManipulator.PDFMergeSortOrder.FileName, True)
Here is the "master" method. As I said, it's probably overkill (and I'm still tweaking it some), but I wanted to do my best to try to make it work as effectively as possible. Obviously it requires a Reference to the itextsharp.dll for access to the library's functions.
I've commented out the references to the Error and Warning properties of the class for this post to help reduce any confusion.
Public Function Merge(ByVal PDFFiles As List(Of System.IO.FileInfo), ByVal OutputFileName As String, ByVal OverwriteExistingPDF As Boolean, ByVal SortOrder As PDFMergeSortOrder) As System.IO.FileInfo
Dim ResultFile As System.IO.FileInfo = Nothing
Dim ContinueMerge As Boolean = True
If OverwriteExistingPDF Then
If System.IO.File.Exists(OutputFileName) Then
Try
System.IO.File.Delete(OutputFileName)
Catch ex As Exception
ContinueMerge = False
'If Errors Is Nothing Then
' Errors = New List(Of String)
'End If
'Errors.Add("Could not delete existing output file.")
Throw
End Try
End If
End If
If ContinueMerge Then
Dim OutputPDF As iTextSharp.text.Document = Nothing
Dim Copier As iTextSharp.text.pdf.PdfCopy = Nothing
Dim PDFStream As System.IO.FileStream = Nothing
Dim SortedList As New List(Of System.IO.FileInfo)
Try
Select Case SortOrder
Case PDFMergeSortOrder.Original
SortedList = PDFFiles
Case PDFMergeSortOrder.FileDate
SortedList = PDFFiles.OrderBy(Function(f As System.IO.FileInfo) f.LastWriteTime).ToList
Case PDFMergeSortOrder.FileName
SortedList = PDFFiles.OrderBy(Function(f As System.IO.FileInfo) f.Name).ToList
Case PDFMergeSortOrder.FileNameWithDirectory
SortedList = PDFFiles.OrderBy(Function(f As System.IO.FileInfo) f.FullName).ToList
End Select
If Not IO.Directory.Exists(New IO.FileInfo(OutputFileName).DirectoryName) Then
Try
IO.Directory.CreateDirectory(New IO.FileInfo(OutputFileName).DirectoryName)
Catch ex As Exception
ContinueMerge = False
'If Errors Is Nothing Then
' Errors = New List(Of String)
'End If
'Errors.Add("Could not create output directory.")
Throw
End Try
End If
If ContinueMerge Then
OutputPDF = New iTextSharp.text.Document
PDFStream = New System.IO.FileStream(OutputFileName, System.IO.FileMode.OpenOrCreate)
Copier = New iTextSharp.text.pdf.PdfCopy(OutputPDF, PDFStream)
OutputPDF.Open()
For Each PDF As System.IO.FileInfo In SortedList
If ContinueMerge Then
Dim InputReader As iTextSharp.text.pdf.PdfReader = Nothing
Try
InputReader = New iTextSharp.text.pdf.PdfReader(PDF.FullName)
For page As Integer = 1 To InputReader.NumberOfPages
Copier.AddPage(Copier.GetImportedPage(InputReader, page))
Next page
If InputReader.IsRebuilt Then
'If Warnings Is Nothing Then
' Warnings = New List(Of String)
'End If
'Warnings.Add("Damaged PDF: " & PDF.FullName & " repaired and successfully merged into output file.")
End If
Catch InvalidEx As iTextSharp.text.exceptions.InvalidPdfException
'Skip this file
'If Errors Is Nothing Then
' Errors = New List(Of String)
'End If
'Errors.Add("Invalid PDF: " & PDF.FullName & " not merged into output file.")
Catch FormatEx As iTextSharp.text.pdf.BadPdfFormatException
'Skip this file
'If Errors Is Nothing Then
' Errors = New List(Of String)
'End If
'Errors.Add("Bad PDF Format: " & PDF.FullName & " not merged into output file.")
Catch PassworddEx As iTextSharp.text.exceptions.BadPasswordException
'Skip this file
'If Errors Is Nothing Then
' Errors = New List(Of String)
'End If
'Errors.Add("Password-protected PDF: " & PDF.FullName & " not merged into output file.")
Catch OtherEx As Exception
ContinueMerge = False
Finally
If Not InputReader Is Nothing Then
InputReader.Close()
InputReader.Dispose()
End If
End Try
End If
Next PDF
End If
Catch ex As iTextSharp.text.pdf.PdfException
ResultFile = Nothing
ContinueMerge = False
'If Errors Is Nothing Then
' Errors = New List(Of String)
'End If
'Errors.Add("iTextSharp Error: " & ex.Message)
If System.IO.File.Exists(OutputFileName) Then
If Not OutputPDF Is Nothing Then
OutputPDF.Close()
OutputPDF.Dispose()
End If
If Not PDFStream Is Nothing Then
PDFStream.Close()
PDFStream.Dispose()
End If
If Not Copier Is Nothing Then
Copier.Close()
Copier.Dispose()
End If
System.IO.File.Delete(OutputFileName)
End If
Throw
Catch other As Exception
ResultFile = Nothing
ContinueMerge = False
'If Errors Is Nothing Then
' Errors = New List(Of String)
'End If
'Errors.Add("General Error: " & other.Message)
If System.IO.File.Exists(OutputFileName) Then
If Not OutputPDF Is Nothing Then
OutputPDF.Close()
OutputPDF.Dispose()
End If
If Not PDFStream Is Nothing Then
PDFStream.Close()
PDFStream.Dispose()
End If
If Not Copier Is Nothing Then
Copier.Close()
Copier.Dispose()
End If
System.IO.File.Delete(OutputFileName)
End If
Throw
Finally
If Not OutputPDF Is Nothing Then
OutputPDF.Close()
OutputPDF.Dispose()
End If
If Not PDFStream Is Nothing Then
PDFStream.Close()
PDFStream.Dispose()
End If
If Not Copier Is Nothing Then
Copier.Close()
Copier.Dispose()
End If
If System.IO.File.Exists(OutputFileName) Then
If ContinueMerge Then
ResultFile = New System.IO.FileInfo(OutputFileName)
If ResultFile.Length <= 0 Then
ResultFile = Nothing
Try
System.IO.File.Delete(OutputFileName)
Catch ex As Exception
Throw
End Try
End If
Else
ResultFile = Nothing
Try
System.IO.File.Delete(OutputFileName)
Catch ex As Exception
Throw
End Try
End If
Else
ResultFile = Nothing
End If
End Try
End If
Return ResultFile
End Function
Some may have to make a change to the code at "writer = PdfWriter.GetInstance(pdfDoc, New FileStream(outputPath, FileMode.OpenOrCreate))" as iTextSharp may not support
Change to:
Dim fs As IO.FileStream = New IO.FileStream(outputPath, IO.FileMode.Create)
writer = iTextSharp.text.pdf.PdfWriter.GetInstance(pdfDoc, fs)

Vb.net the process cannot access the file because it is being used by another process

Hello i wanted to open an csv file and write text in it.
Here is the code:
Try
Dim path As String = "C:\Users\daaemoon\Desktop\Test.csv"
Dim reader As StreamReader = New System.IO.StreamReader(File.OpenRead(path))
Dim sw As New StreamWriter(path)
Dim s As String = String.Empty
While reader.Peek() >= 0
Dim line As String = reader.ReadLine()
Dim values As String() = line.Split(";"c)
listforfalsecsv.Add(values(0))
s = s + line + Chr(10)
End While
reader.Close()
sw.Write(s)
sw.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
i got the error by the following line:
Dim sw As New StreamWriter(path)
If i use the method reader.dispose() after that line Dim reader As StreamReader = New System.IO.StreamReader(File.OpenRead(path))
i come to the while loop, but than i got an error: From an closen Textreader could not been read.
I need help, please help me.

VB.NET - Problems trying to write a textfile

I have problems when trying to delete/create/write to this file.
The error:
The process cannot access the file 'C:\Users\Administrador\AppData\Local\Temp\PlayList_temp.txt' because it is being used by another process.
The highlighted lines by debugger:
If System.IO.File.Exists(Temp_file) = True Then System.IO.File.Delete(Temp_file)
System.IO.File.Create(Temp_file)
(Any of two, if I delete one line, the other line takes the same error id)
The sub:
Public Sub C1Button2_Click(sender As Object, e As EventArgs) Handles Button1.Click
If Not playerargs = Nothing Then
Dim Str As String
Dim Pattern As String = ControlChars.Quote
Dim ArgsArray() As String
Dim Temp_file As String = System.IO.Path.GetTempPath & "\PlayList_temp.txt"
Dim objWriter As New System.IO.StreamWriter(Temp_file)
Str = Replace(playerargs, " " & ControlChars.Quote, "")
ArgsArray = Split(Str, Pattern)
If System.IO.File.Exists(Temp_file) = True Then System.IO.File.Delete(Temp_file)
System.IO.File.Create(Temp_file)
For Each folder In ArgsArray
If Not folder = Nothing Then
Dim di As New IO.DirectoryInfo(folder)
Dim files As IO.FileInfo() = di.GetFiles("*")
Dim file As IO.FileInfo
For Each file In files
' command to writleline
'Console.WriteLine("File Name: {0}", file.Name)
'Console.WriteLine("File Full Name: {0}", file.FullName)
objWriter.Write(file.FullName)
objWriter.Close()
Next
End If
Next
If randomize.Checked = True Then
RandomiseFile(Temp_file)
End If
Process.Start(userSelectedPlayerFilePath, playerargs)
If autoclose.Checked = True Then
Me.Close()
End If
Else
MessageBox.Show("You must select at least one folder...", My.Settings.APPName)
End If
End Sub
First, File.Create creates or overwrite the file specified, so you don't need to Delete it before.
Second, initializing a StreamWriter as you do, blocks the file and therefore you can't recreate it after.
So, simply move the StreamWriter intialization after the File.Create, or better, remove altogether the File.Create and use the StreamWriter overload that overwrites the file
....
If Not playerargs = Nothing Then
....
Dim Temp_file As String = System.IO.Path.GetTempPath & "\PlayList_temp.txt"
Using objWriter As New System.IO.StreamWriter(Temp_file, false)
For Each folder In ArgsArray
If Not folder = Nothing Then
Dim di As New IO.DirectoryInfo(folder)
Dim files As IO.FileInfo() = di.GetFiles("*")
Dim file As IO.FileInfo
For Each file In files
' command to writleline
'Console.WriteLine("File Name: {0}", file.Name)
'Console.WriteLine("File Full Name: {0}", file.FullName)
objWriter.Write(file.FullName)
' objWriter.Close()
Next
End If
Next
End Using ' Flush, close and dispose the objWriter
....
Noticed also that you close the writer while still inside the loop, use the Using statement to close correctly the writer after the work is done.
The process cannot access the file 'C:\Users\Administrador\AppData\Local\Temp\PlayList_temp.txt' because it is being used by another process.
That means the file is opened or been used by another process.
Open your task manager and check if the file is there, then close it or simplex end the process.
I have had the same issue but I got it solved by closing the file.
Hope this helps!
From your details it seems that you are willing to delete if file exists and creates a new one.
I would suggest to remove this line:
System.IO.File.Create(Temp_file)
and move this line just over the streamwriter line:
If System.IO.File.Exists(Temp_file) = True Then System.IO.File.Delete(Temp_file)
Something like this would help you:
Partial code:
Dim Temp_file As String = System.IO.Path.GetTempPath & "\PlayList_temp.txt"
' Delete file if exists
If System.IO.File.Exists(Temp_file) = True Then System.IO.File.Delete(Temp_file)
' Create file for write.
Dim objWriter As New System.IO.StreamWriter(Temp_file)
Str = Replace(playerargs, " " & ControlChars.Quote, "")
ArgsArray = Split(Str, Pattern)
...
...
...