VB.NET code to reverse file contents - vb.net

I have wrote some code in Visual Basic 6 which reverses the contents of a file, however I have problems converting this code to .NET as VB.NET only reads the text part of the file. Can someone please show me the VB.NET equivalent of this code. I believe it will not only help me, but the whole SOF community :).
Public Function NeutralizeFile(strFile As String, strOut As String) As Boolean
On Error GoTo ErrDelete
Dim File As String
Open strFile For Binary As #1
File = Space(LOF(1))
Get #1, , File
Close #1
File = StrReverse(File)
Open strOut For Binary As #1
Put #1, , File
Close #1
Kill strFile
ErrDelete:
End Function

Public Sub NeutralizeFile(ByVal PathIn As String, ByVal PathOut As String)
Try
Dim data() As Byte = IO.File.ReadAllBytes(PathIn)
Array.Reverse(data)
IO.File.WriteAllBytes(PathOut, data)
Catch ex As Exception
MsgBox("Error")
End Try
End Sub

Try this
Public Sub NeutralizeFile(strFile As String, strOut As String)
Try
Dim StreamReader1 As New IO.StreamReader(strFile)
Dim StreamWriter1 As New IO.StreamWriter(strOut)
StreamWriter1.Write(StrReverse(StreamReader1.ReadToEnd))
StreamReader1.Close()
StreamReader1.Dispose()
StreamWriter1.Close()
StreamWriter1.Dispose()
IO.File.Delete(strFile)
Catch ex As Exception
MsgBox("Error")
End Try
End Sub

Related

Why am I getting an error when I try to print the contents of a file I am searching for?

Can you help me with searching for and printing a file specified by text in textbox1? I have the following code but textbox1 shows me an error. I don't know if the code is correctly written and functioning right.
First class:
Public Class tisk
'print
Public Shared Function printers()
Dim printThis
Dim strDir As String
Dim strFile As String
Dim Textbox1 As String
strDir = "C:\_Montix a.s. - cloud\iMontix\Testy"
strFile = "C:\_Montix a.s. - cloud\iMontix\Testy\" & Textbox1.text & ".lbe"
If Not fileexprint.FileExists Then
MsgBox("Soubor neexistuje")
printers = False
Else
fileprint.PrintThisfile()
printers = True
End If
End Function
End Class
Second class:
Public Class fileprint
Public Shared Function PrintThisfile()
Dim formname As Long
Dim FileName As String
On Error Resume Next
Dim X As Long
X = Shell(formname, "Print", FileName, 0&)
End Function
End Class
Third class:
Public Class fileexprint
Public Shared Function FileExists()
Dim fname As Boolean
' Returns TRUE if the file exists
Dim X As String
X = Dir(fname)
If X <> "" Then FileExists = True _
Else FileExists = False
End Function
End Class
When I fill a textbox with text, how can I search for a file in the computer using this text and print this file?
Your "Textbox1" is a variable and not actually getting the value from a textbox. If I'm not wrong, I believe you intend to get the value of a textbox and concatenate to form your directory url. You'll first need to add a text box to your windows/web form, give that textbox an id then call that id in your code behind. E.g. You add a text box with id "textbox001", in your code behind you'll do something like "textbox001.text". In your case it'll now be: strFile = "C:_Montix a.s. - cloud\iMontix\Testy\" & textbox001.text & ".lbe". Hope this helps.
Not sure this will fix your issue, but there are some poor practices in that code that are addressed below. This will certainly get you closer than what you have right now.
Public Class tisk
'print
Public Shared Function printers(ByVal fileName As String) As Boolean
Dim basePath As String = "C:\_Montix a.s. - cloud\iMontix\Testy"
Dim filePath As String = IO.Path.Combine(basePath, fileName & ".lbe")
If IO.File.Exists(filePath) Then
fileprint.PrintThisfile(filePath)
Return True
End If
'Don't show a message box here. Do it in the calling code
Return False
End Function
End Class
Public Class fileprint
Public Shared Sub PrintThisfile(ByVal fileName As String)
'Not sure how well this will work, but it has better chances than the original
Dim p As New Process()
p.StartInfo.FileName = fileName
p.StartInfo.Verb = "Print"
p.Start()
End Sub
End Class
One additional comment on the File.Exists() check. It's actually poor practice to check if the file exists here at all. The file system is volatile. It's possible for things to change in the short time between when you check and when you try to use the file. In addition, whether the file exists is only one thing you need to look at. There's also access permissions and whether the file is locked or in use. The better practice is to just try to do whatever you need with the file, and then handle the exception if it fails.

Detect if any file in use by other process of a directory in VB

I am trying to get my vb.net application to look inside a folder and then let me know whether any file older is in use by any application. If in use it will show a message box. I am coding in VB.NET 2008, Express Edition. ...Would anybody know how I do that? Thanks
You can extend the suggested solution with enumerating files in a directory.
Imports System.IO
Imports System.Runtime.InteropServices
Module Module1
Sub Main()
' Here you specify the given directory
Dim rootFolder As DirectoryInfo = New DirectoryInfo("C:\SomeDir")
' Then you enumerate all the files within this directory and its subdirectory
' See System.IO.SearchOption enum for more info
For Each file As FileInfo In rootFolder.EnumerateFiles("*.*", SearchOption.AllDirectories)
' Here you can call the method from the solution linked in Sachin's comment
IsFileOpen(file)
Next
End Sub
' Jeremy Thompson's code from here
Private Sub IsFileOpen(ByVal file As FileInfo)
Dim stream As FileStream = Nothing
Try
stream = file.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None)
stream.Close()
Catch ex As Exception
If TypeOf ex Is IOException AndAlso IsFileLocked(ex) Then
' do something here, either close the file if you have a handle, show a msgbox, retry or as a last resort terminate the process - which could cause corruption and lose data
End If
End Try
End Sub
Private Function IsFileLocked(exception As Exception) As Boolean
Dim errorCode As Integer = Marshal.GetHRForException(exception) And ((1 << 16) - 1)
Return errorCode = 32 OrElse errorCode = 33
End Function
End Module

How to check if sub-folder text file exists

I am trying to search if a text file in a sub-folder exists.
This is the code I am using:
'Checks the program's root folder to see if the root folder exists.
Dim FolderName = New DirectoryInfo(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Cake Orders\" & TextBox1.Text))
Dim McKnwoll As String = Path.Combine(FolderName.FullName, Trim(TextBox2.Text) & (" ") & Trim(TextBox3.Text) + ".RTO")
If Not McKnwoll.Exists Then
‘Message to user that file does not exist in sub-folder
Else
‘Message to user that file does exists in sub-folder
End If
I am getting an error that 'Exists' is not a member of 'String'. How can I re-work my code to check if the text file whose name is in the format of "TextBox2.Text & (" ") & TextBox3.Text + ".RTO"; exists.
I am using Visual Basic 2010 Express. Thank you.
File.Exists returns a Boolean indicating whether a file at a certain path exists:
If File.Exists(pathToFile) Then
...
End If
Be sure to include Imports System.IO at the top of your source code file.
You seem quite new in programming. Welcome.
That error message you got ('Exists' is not a member of 'String') tells you exactely what is wrong: You try to ask a string (some text) whether it exists, but what you like to do is to ask a file whether it exists.
The class that provides information about a file is called "FileInfo", and FileInfo has an "Exists" property that you can call:
Dim myFileInfo As New FileInfo(McKnwoll)
If myFileInfo.Exists Then
'do something
End If
That's the object oriented answer, Heinzi's more service oriented one but works, of course, too.
There have been several other small issues I noticed with your code, e.g.
"Cake Orders\" & TextBox1.Text
does not use Path.Combine but makes a string concatenation using fix a "\" as directory separater. Or that the DirectoryInfo is not really used here, the string to the folder is enough.
You also try to handle 3 different issues (reading the values from the user interface, constructing the fullname of the file, checking whether the file exists) in one single code block. I would split them into 3 different ones (actually 4, I would add another one for displaying error messages).
Your simple few lines of codes could be complicated like this ;-)
Imports System.IO
Imports System.Text
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
ReadFileIfPossible(TextBox1.Text, TextBox2.Text, TextBox3.Text)
End Sub
Private Sub ReadFileIfPossible(subfolder As String, part1 As String, part2 As String)
'Get the path to the RTO file
Dim myFilePath As String = Nothing
Try
myFilePath = GetRtoFilePath(subfolder, part1, part2)
Catch ex As Exception
DisplayErrorMessage("Error constructing file name! Please check the values of TextBox1, TextBox2 and TextBox3.")
Return
End Try
'Get the file info
Dim myFile As FileInfo = Nothing
Try
myFile = New FileInfo(myFilePath)
Catch ex As Exception
DisplayErrorMessage(ex.Message)
Return
End Try
'Check whether it exists
Dim myExists As Boolean = False
Try
myExists = myFile.Exists 'it's IO, everything might throw an exception...
Catch ex As Exception
DisplayErrorMessage(ex.Message)
Return
End Try
'Display message if not found
If (Not myExists) Then
DisplayErrorMessage("File ""{0}"" could not be found!", myFilePath)
Return
End If
'Read the file
Dim myLines As String() = Nothing
Try
myLines = File.ReadAllLines(myFile.FullName, New UTF8Encoding(True))
Catch ex As Exception
DisplayErrorMessage(ex.Message)
Return
End Try
'Do something with it...
End Sub
Private Shared Function GetRtoFilePath(subfolder As String, part1 As String, part2 As String) As String
'Check args
If (subfolder Is Nothing) Then Throw New ArgumentNullException("subfolder")
If (part1 Is Nothing) Then Throw New ArgumentNullException("part1")
If (part2 Is Nothing) Then Throw New ArgumentNullException("part2")
'Normalize args
part1 = part1.Trim()
part2 = part2.Trim()
'Build path
Dim myDesktopPath As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
Dim myFolderPath As String = Path.Combine(myDesktopPath, "Cake Orders")
myFolderPath = Path.Combine(myFolderPath, subfolder)
Dim myFileName As String = String.Format("{0} {1}.RTO", part1, part2)
Dim myResult As String = Path.Combine(myFolderPath, myFileName)
myResult = Path.GetFullPath(myResult)
'Return result
Return myResult
End Function
Private Sub DisplayErrorMessage(message As String, ParamArray args As Object())
Dim myMsg As String = String.Format(message, CType(args, Object()))
MsgBox(myMsg, MsgBoxStyle.OkOnly, "Error")
End Sub
End Class
Have fun.

Avoid exiting a for/next on error

I should know better than to not give enough information/good information when asking for help. I have another question which I need to delete/link or merge here... any comment on how to do that would be great.
So the problem is I am trying to write a simple app (yeah, right) to locate a specific file on the local HDD. There WILL be multiple instances of the file (backups etc.) and I want to find each. Issues are that I cannot know how many local hdd there are and I cannot know what directory the file might be in.
So I wanted to
iterate through all fixed HDD
search the hdd for the file (I always know the name of the file)
I search HDD like this...
For Each drive As IO.DriveInfo In IO.DriveInfo.GetDrives
If drive.DriveType.ToString = "Fixed" Then
So if the found hdd is fixed I do this...
Try
For Each filename As String In IO.Directory.GetFiles(hdd, "user.config", IO.SearchOption.AllDirectories)
The issue is that I throw an exception, I have the for block above in a try catch, the exception is caught and the code exits.
OK, so I guess this is to be expected. Any suggestions on how to avoid this? Meaning I know I will run across files/directories I do not have permission for, how do I carry on and ignore what I don't care about?
FULL CODE LISTING
Private Sub Command1_Click(sender As System.Object, e As System.EventArgs) Handles Command1.Click
'variable to hold each hdd name eg: c:\
Dim hdd As String
Dim directories As Integer = 0
Dim files As Integer = 0
Try
For Each drive As IO.DriveInfo In IO.DriveInfo.GetDrives
If drive.DriveType.ToString = "Fixed" Then
'asign the variable hdd a name for this run through
hdd = drive.Name
'assign label value for directories
directories = directories + 1
Label6.Text = directories.ToString
Me.Refresh()
'search the hdd for the file user.config
Try
For Each filename As String In IO.Directory.GetFiles(hdd, "user.config", IO.SearchOption.AllDirectories)
Me.Refresh()
' 'assign label value for files
files = files + 1
Label2.Text = files.ToString
Me.Refresh()
' 'variable to hold the path for each found file
Dim file As String = IO.Path.GetFullPath(filename)
' 'update file checking label
Label4.Text = file.ToString
' 'add each found file to the list
List1.Items.Add(file)
Next
Catch ex As Exception
End Try
End If
Next
Catch ex As Exception
MsgBox(ex.ToString)
End Try
'iterate through each found drive
End Sub
You need to write it out long-wise because you need to handle the IO security issues. And of course a recursive function.
Called by:
FindFileOnAllDrivesOfType(System.IO.DriveType.Fixed, "test.txt")
Methods:
Public Function FindFileOnAllDrivesOfType(ByVal DriveType As System.IO.DriveType, ByVal FileToFind As String) As List(Of String)
Dim AllLocations As New List(Of String)
For Each drive As IO.DriveInfo In IO.DriveInfo.GetDrives
If drive.DriveType = DriveType Then
AllLocations = FindFile(drive.ToString(), FileToFind)
End If
Next
Return AllLocations
End Function
Public Function FindFile(ByVal StartDirectory As String, ByVal FileToFind As String) As List(Of String)
Dim AllLocations As New List(Of String)
Try
For Each dirname As String In IO.Directory.GetDirectories(StartDirectory)
AllLocations.AddRange(FindFile(dirname, FileToFind))
Next
For Each filename As String In IO.Directory.GetFiles(StartDirectory, FileToFind, IO.SearchOption.TopDirectoryOnly)
AllLocations.Add(filename)
Next
Catch ex As Exception
' MessageBox.Show(ex.Message)
'Do nothing as we can't get a directory listing
End Try
Return AllLocations
End Function

ASP.NET How do I wait for file upload/release?

I've got ASP.NET intranet application written in VB. It gets a file from the user, and then depending on a few different cases it may create a few copies of the file as well as move the original.
Unfortunately I've come across a case where I get this error:
Exception Details: System.IO.IOException: The process cannot access the file
'\\some\dir\D09_03_5_180_0.000-6.788.png' because it is being used by
another process.
Which is thrown by My.Computer.FileSystem.CopyFile. And that's fine that it's being used by another process - it may still be saving/downloading from the user or trying to copy while another thread(?) is copying, I don't really care about that, what I want to know:
Is there any way that I can tell VB to wait to copy (also move) the file until the file is no longer in use?
Thanks
Test if the file is in use and the do what you need to do.
Public Sub WriteLogFile(ByVal pText As String, ByVal psPath As String, ByVal psName As String)
Dim strFullFileName As String
Dim Writer As System.IO.StreamWriter
Dim Fs As System.IO.FileStream
Try
Dim DirectoryHandler As New System.IO.DirectoryInfo(psPath)
strFullFileName = psPath & "\" & psName & Date.Today.Month.ToString & "-" & Date.Today.Day.ToString & "-" & Date.Today.Year.ToString & ".txt"
If Not DirectoryHandler.Exists() Then
Try
Monitor.Enter(fsLocker)
DirectoryHandler.Create()
Finally
Monitor.Exit(fsLocker)
End Try
End If
Try
If CheckIfFileIsInUse(strFullFileName) = True Then
Thread.Sleep(500) ' wait for .5 second
WriteLogFile(pText, psPath, psName)
If Not Fs Is Nothing Then Fs.Close()
If Not Writer Is Nothing Then Writer.Close()
Exit Sub
End If
Monitor.Enter(fsLocker)
Fs = New System.IO.FileStream(strFullFileName, IO.FileMode.Append, IO.FileAccess.Write, IO.FileShare.Write)
Writer = New System.IO.StreamWriter(Fs)
Writer.WriteLine(Date.Now.ToString & vbTab & "ProcessID: " & Process.GetCurrentProcess.Id.ToString() & vbTab & pText)
Writer.Close()
Fs.Close()
Finally
Monitor.Exit(fsLocker)
End Try
Catch ex As Exception
Dim evtEMailLog As System.Diagnostics.EventLog = New System.Diagnostics.EventLog()
evtEMailLog.Source = Process.GetCurrentProcess.ProcessName.ToString()
evtEMailLog.WriteEntry(ex.Message, System.Diagnostics.EventLogEntryType.Error)
Finally
If Not Fs Is Nothing Then Fs.Close()
If Not Writer Is Nothing Then Writer.Close()
End Try
End Sub
Public Function CheckIfFileIsInUse(ByVal sFile As String) As Boolean
If System.IO.File.Exists(sFile) Then
Try
Dim F As Short = FreeFile()
FileOpen(F, sFile, OpenMode.Append, OpenAccess.Write, OpenShare.Shared)
FileClose(F)
Catch
Return True
End Try
End If
End Function
Hmm... not directly.
What most implementations are doing, is making a retry of copying the file, with a small timeframe (some seconds)
if you want to make a nice UI, you check via Ajax, if the copying process went well.
Well, it turns out that waiting would not work in this case:
When trying to copy a file you cannot copy a file from one location to the same location or it will throw an error (apparently). Rather than just pretending to copy the file, VB actually tries to copy the file and fails because the copy operation is trying to copy to the file it's copying from (with overwrite:=True at least).
Whoops!