Is there any tool to convert multiline text for Visual Studio 2008/2005? - vb.net

Is there any tool that will convert a multiline text, to a compatible multiline string for Visual Studio 2008/2005?
For example:
line1
line2
line3
line4
Should become:
"line1" & _
"line2" & _
"line3" & _
"line4"

This kind of tool definitely falls in the do-it-yourself category. Start a new Windows Forms application. Paste the code shown below. Put a shortcut to the program on your desktop. To use it, drag a file from Explorer onto the form. Switch to Visual Studio and type Ctrl+V.
Public Class Form1
Public Sub New()
InitializeComponent()
Me.AllowDrop = True
End Sub
Protected Overrides Sub OnDragEnter(ByVal e As DragEventArgs)
If e.Data.GetDataPresent("FileDrop") Then e.Effect = DragDropEffects.Copy
End Sub
Protected Overrides Sub OnDragDrop(ByVal e As DragEventArgs)
Dim files = DirectCast(e.Data.GetData("FileDrop", False), String())
Dim txt As New System.Text.StringBuilder
Dim lines = System.IO.File.ReadAllLines(files(0))
For ix As Integer = 0 To lines.Length - 1
txt.Append("""" + lines(ix).Replace("""", """""") + """")
If ix < lines.Length - 1 Then txt.AppendLine(" & _")
Next
Clipboard.SetText(txt.ToString())
End Sub
End Class
The better mousetrap is to add the file as a resource instead of hard-coding the text.

Is this what you're looking for?
Dim testString As String = "line1" & vbCrLf & _
"line2" & vbCrLf & _
"line3" & vbCrLf & _
"line4"
Dim allLines() As String = Microsoft.VisualBasic.Strings.Split(testString, vbCrLf)
Dim strConverter As New System.Text.StringBuilder
For Each line As String In allLines
strConverter.Append("""" & line & """").Append(" & _").Append(vbCrLf)
Next
If allLines.Length > 0 Then strConverter.Length -= (" & _" & vbCrLf).Length
Dim convertedString As String = strConverter.ToString

A VS Macro for Pasting Long Text as String seems like perfect solution.

Related

Unable to open txt file path

This code runs perfectly when I hard code the path to the textfile. But as suggested, it is much better not to hard code stuff. I tried it this way and still can't find the txt file even if it exists.
Dim Findstring = IO.File.ReadAllText(Directory.GetCurrentDirectory() + " Redmi03-JCO0531-WX_" + DateTime.Now.ToString("yyyyMMdd") + ".txt")
Dim Lookfor As String = Format(Now, "MM/dd/yyyy HH:mm:ss")
'MessageBox.Show(Findstring.ToString())
showdat.Text = Lookfor
If Findstring.Contains(Lookfor) Then
'MsgBox("Found: " & Lookfor)
For Each prog As Process In Process.GetProcesses
If prog.ProcessName = "Redmi03-JCO0531-WX" Then
prog.Kill()
Process.Start(Directory.GetCurrentDirectory() + "Redmi03-JCO0531-WX.exe")
End If
Next
End If
I guess your problem is at this line
Dim Findstring = IO.File.ReadAllText(Directory.GetCurrentDirectory() + " Redmi03-JCO0531-WX_" + DateTime.Now.ToString("yyyyMMdd") + ".txt")
Let's break that down and see what each part really is.
First at the top of the code file add
Imports System.IO
Then in your Form class
Private Sub OPCode()
Dim dir As String = Directory.GetCurrentDirectory()
MessageBox.Show(dir)
Dim TextFileName = " Redmi03-JCO0531-WX_" & DateTime.Now.ToString("yyyyMMdd") & ".txt"
MessageBox.Show(TextFileName)
Dim CompletePath = Path.Combine(dir, TextFileName)
MessageBox.Show(CompletePath)
Dim Findstring = IO.File.ReadAllText(CompletePath)
End Sub
Actually, you can add a break point and step through the code checking the values of your in your code instead of all these silly Message Boxes. If the 3rd MessageBox does not show the actual location of your file then it is back to the drawing board.
EDIT
Edit to get path on desktop.
Private Sub OPCode()
Dim dir As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
MessageBox.Show(dir)
Dim TextFileName = "ChinaUMS Bank\Redmi05\Redmi03-JCO0531-WX_" & DateTime.Now.ToString("yyyyMMdd") & ".txt"
MessageBox.Show(TextFileName)
Dim CompletePath = Path.Combine(dir, TextFileName)
MessageBox.Show(CompletePath)
' Dim Findstring = IO.File.ReadAllText(CompletePath)
End Sub
Notice that you must hardcode the sub-folders. The special folder will get the Desktop path for the current user.

Saving data with a file name of my choice

Very kindly, an intelligent member of stack overflow showed me how to loop with 'Do Until' and generate messages boxes to enable a user to save a file or rename one, if it already exists. However, I'm still hitting a wall. I can't save the ListView data in my for loop, with the file name I have chosen in the Input Box (see code below). Its like I have two separate pieces of code because rtb is saving data in a Rich Text File called Test.txt and saveFile has nothing to do with this! Please help
Code
Dim fileSaved As Boolean
Do Until fileSaved
Dim saveFile As String = InputBox("Enter a file name to save this message")
If saveFile = "" Then Exit Sub
Dim docs As String = My.Computer.FileSystem.SpecialDirectories.MyDocuments
Dim filePath As String = IO.Path.Combine(docs, "Visual Studio 2013\Projects", saveFile & ".txt")
fileSaved = True
If My.Computer.FileSystem.FileExists(filePath) Then
Dim msg As String = "File Already Exists. Do You Wish To Overwrite it?"
Dim style As MsgBoxStyle = MsgBoxStyle.YesNo Or MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Critical
fileSaved = (MsgBox(msg, style, "Warning") = MsgBoxResult.Yes)
End If
Loop
'THIS NEXT bit of code saves content to Test.txt NOT saveFile as desired!
Dim rtb As New RichTextBox
rtb.AppendText("Generation, Num Of Juveniles, Num of Adults, Num of Semiles, Total" & vbNewLine)
For Each saveitem As ListViewItem In ListView1.Items
rtb.AppendText(
saveitem.Text & ", " &
saveitem.SubItems(1).Text & ", " &
saveitem.SubItems(2).Text & ", " &
saveitem.SubItems(3).Text & ", " &
saveitem.SubItems(4).Text & vbNewLine)
Next
rtb.SaveFile("C:\Users\SMITH\Documents\Visual Studio 2013\Projects\Test.txt", _
RichTextBoxStreamType.PlainText)
When you try to save the file with the RichTextBox method SaveFile you need to be able to use the variable filePath that receive the input from your user. But this variable is declared inside the block Do Until .... Loop and according to scope rules of variables in VB.NET is not available outside that block. You could move the declaration of the variable before entering the loop
Dim fileSaved As Boolean
Dim filePath As String
Do Until fileSaved
Dim saveFile As String = InputBox("Enter a file name to save this message")
If saveFile = "" Then Exit Sub
Dim docs as String = My.Computer.FileSystem.SpecialDirectories.MyDocuments
filePath = IO.Path.Combine(docs, "Visual Studio 2013\Projects", saveFile & ".txt")
fileSaved = True
If My.Computer.FileSystem.FileExists(filePath) Then
Dim msg As String = "File Already Exists. Do You Wish To Overwrite it?"
Dim style As MsgBoxStyle = MsgBoxStyle.YesNo Or MsgBoxStyle.DefaultButton2 Or MsgBoxStyle.Critical
fileSaved = (MsgBox(msg, style, "Warning") = MsgBoxResult.Yes)
End If
Loop
' The remainder of your code can be left unchanged until the SaveFile line
Now you could use it in the call
rtb.SaveFile(filePath, RichTextBoxStreamType.PlainText)

Automatically format a long outerXml string

I have multiple large XML files and am trying to extract 5 instances of a specific element and its children. I have the code all set, however, I HAVE to use StreamWriter to write out the xml. How can I do this so that it comes out properly indented, etc.
The string looks similar to this:
<SampleMAIN><Sample type="1"><Sample_Batch>123
</Sample_Batch><SampleMethod>
</SampleMethod>
</Sample></SampleMAIN>
I want it to look like this:
<SampleMAIN>
<Sample type="1">
<Sample_Batch>123
</Sample_Batch>
<SampleMethod>1
</SampleMethod>
</SampleMAIN>
With using StreamWriter, the below code will output the format that you need and append to an existing xml file.
Private Sub Button1_Click(sender As System.Object, _
e As System.EventArgs) Handles Button1.Click
Dim sw As System.IO.StreamWriter
Dim St As String = "1"
Dim Sb As String = "123"
Dim Sm As String = "1"
sw = File.AppendText("C:\XML_Files\sampler_02.xml")
sw.WriteLine("<SampleMAIN>")
sw.WriteLine(" <Sample type=" & """" & St & """" & ">")
sw.WriteLine(" <Sample_Batch>" & Sb)
sw.WriteLine(" </Sample_Batch>")
sw.WriteLine(" <SampleMethod>" & Sm)
sw.WriteLine(" </SampleMethod>")
sw.WriteLine("</SampleMAIN>")
sw.Close()
End Sub
So for anyone who may come across this and was interested in how I resolved it, here is what I used...
Dim dir As New DirectoryInfo("D:\data")
Dim sw As New StreamWriter("C:\Documents\largeFile.xml")
Dim xd As New XmlDocument
Dim iCount As Integer
sw.WriteLine("<?xml version=""1.0"" encoding=""ISO-8859-1""?>" & vbCrLf & "<Root>")
For Each fi As FileInfo In dir.GetFiles()
xd.Load(fi.FullName)
iCount = 0
For Each xn As XmlNode In xd.SelectNodes("//Root")
For Each xe As XmlElement In xn.ChildNodes
iCount += 1
sw.WriteLine(xe.OuterXml.ToString)
If iCount = 5 Then Exit For
Next
Exit For
Next
Next
sw.WriteLine("</Root>")
sw.Flush() : sw.Close() : sw.Dispose()

Visual Basic - system.nullReferenceException

So I'm still a bit of a newbie when it comes to programming, hence why I'm using visual basic. I'm getting this exception raised repeatedly, but the variables that vb is saying have unassigned values have been given values in my code. Can anyone point out where I'm going wrong with this?
EDIT: just a few more details: the file exists, I can read from it using just the ReadLine method, but I need to split the fields so I can compare the scores and get the highest 2 scores
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim srdFile As System.IO.StreamReader
Dim strLine As String
Dim strField(1) As String
Dim strName() As String
Dim strScore() As String
Dim i = 0
srdFile = New System.IO.StreamReader("HighScores.dat")
rtbOut.AppendText("HighScores:" & vbNewLine & vbNewLine)
Do Until srdFile.Peek() = -1
strLine = srdFile.ReadLine()
strField = strLine.Split(",")
strName(i) = strField(0)
strScore(i) = strField(1)
rtbOut.AppendText(strName(i) & ", " & strScore(i) & vbNewLine)
i = i + 1
Loop
End Sub
Following two arrays are never initialized: strName and strScore
I don't know the logic, but one way would be to use a List(Of String) instead which does not need to get the correct size in the first place and can be resized. I would also use the Using-statement to dispose the stream properly:
Using srdFile As New System.IO.StreamReader("HighScores.dat")
Dim strLine As String
Dim strField(1) As String
Dim strName As New List(Of String)
Dim strScore As New List(Of String)
Dim i = 0
rtbOut.AppendText("HighScores:" & vbNewLine & vbNewLine)
Do Until srdFile.Peek() = -1
strLine = srdFile.ReadLine()
strField = strLine.Split(","c)
strName.Add(strField(0))
strScore.Add(strField(1))
rtbOut.AppendText(strName(i) & ", " & strScore(i) & vbNewLine)
i += 1
Loop
End Using
Side-note: i recommend to set Option Strict to On by default.
By the way, here is a completely different approach doing the same but with LINQ:
Dim lines = From line In IO.File.ReadLines("HighScores.dat")
Where Not String.IsNullOrWhiteSpace(line)
Let fields = line.Split(","c)
Let name = fields.First()
Let score = fields.Last()
Select String.Format("{0}, {1}", name, score)
rtbOut.Text = String.Join(Environment.NewLine, lines)
I find this more readable.
Before you use an array, you need to assign a fixed array size in the computer memory locations. You can do this by initialising an array with the number of array elements. In your code, you have not allocated any memory to strName() and strScore() before using them, hence the code will throw an exception.
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim srdFile As System.IO.StreamReader
Dim strLine As String
Dim strField(1) As String
Dim strName(10) As String ''fixed size array (Using List(Of T) is a better option)
Dim strScore(10) As String ''fixed size array (Using List(Of T) is a better option)
Dim i = 0
srdFile = New System.IO.StreamReader("HighScores.dat")
rtbOut.AppendText("HighScores:" & vbNewLine & vbNewLine)
Do Until srdFile.Peek() = -1
strLine = srdFile.ReadLine()
strField = strLine.Split(",")
strName(i) = strField(0)
strScore(i) = strField(1)
rtbOut.AppendText(strName(i) & ", " & strScore(i) & vbNewLine)
i = i + 1
Loop
End Sub
You can also create a dynamic array. Please follow Resizing an array at runtime in VB.NET on Stackoverflow about dynamic array.

How to replace multiple consective lines in a line and skip the header for that section

I need to find a section header, in this case "[Store Hours]", in a text file that I'm using to save the settings for the program. I need to skip the header and replace the next 7 lines with the text that is in the text boxes. The code below currently deletes the header "[Store Hours]" and does not replace any of the lines.
Dim objFileName As String = "Settings.txt"
Private Sub BtnAdd_Click(sender As System.Object, e As System.EventArgs) Handles btnSaveHours.Click
Dim OutPutLine As New List(Of String)()
Dim matchFound As Boolean
For Each line As String In System.IO.File.ReadAllLines(objFileName)
matchFound = line.Contains("[Store Hours]")
If matchFound Then
'does not skip the header line
line.Skip(line.Length)
'Need to loop through this 7 times (for each day of the week)
'without reading the header again
For intCount = 0 To 6
Dim aryLabelDay() As String = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}
Dim varLabelNameIn As String = "txt" & aryLabelDay(intCount).ToString & "In"
Dim varDropNameIn As String = "drp" & aryLabelDay(intCount).ToString & "In"
Dim varLabelNameOut As String = "txt" & aryLabelDay(intCount).ToString & "Out"
Dim varDropNameOut As String = "drp" & aryLabelDay(intCount).ToString & "Out"
Dim varTextBoxInControl() As Control = Me.Controls.Find(varLabelNameIn, True)
Dim varDropBoxInControl() As Control = Me.Controls.Find(varDropNameIn, True)
Dim varTextBoxOutControl() As Control = Me.Controls.Find(varLabelNameOut, True)
Dim varDropBoxOutControl() As Control = Me.Controls.Find(varDropNameOut, True)
Dim dymTextNameIn As TextBox = DirectCast(varTextBoxInControl(0), TextBox)
Dim dymDropNameIn As ComboBox = DirectCast(varDropBoxInControl(0), ComboBox)
Dim dymTextNameOut As TextBox = DirectCast(varTextBoxOutControl(0), TextBox)
Dim dymDropNameOut As ComboBox = DirectCast(varDropBoxOutControl(0), ComboBox)
Dim ReplaceLine As String
ReplaceLine = dymTextNameIn.Text & "," & dymDropNameIn.Text & "," & dymTextNameOut.Text & "," & dymDropNameOut.Text
'this doesn't replace anything
line.Replace(line, ReplaceLine)
intCount += 1
Next intCount
Else
OutPutLine.Add(line)
End If
Next
End Sub
Instead of using ReadAllLines simply use a streamreader and read the file line by line, like this;
Dim line As String
Using reader As StreamReader = New StreamReader("file.txt")
' Read one line from file
line = reader.ReadLine
If(line.Contains("[Store Hours]") Then
'The current line is the store hours header, so we skip it (read the next line)
line = reader.ReadLine
'Process the line like you want, and keep processing through the lines by doing a readline each time you want to progress to the next line.
End If
End Using
More importantly though, you should not be saving the settings for your program in a text file. They should be stored in app.config or web.config. See this question for further guidance on that.
Part of your confusion might be coming from the fact that you can't just replace part of a text file without copying it and overwriting it. One way, to do this, is to copy the file to memory changing the appropriate lines and overwriting the existing file with the new information. Here's one way that can be done:
Private Sub BtnAdd_Click(sender As System.Object, e As System.EventArgs) Handles btnSaveHours.Click
Dim OutPutLine As New List(Of String)()
Dim sr As New StreamReader(objFileName)
While Not sr.EndOfStream
Dim line = sr.ReadLine
'Found the header so let's save that line to memory and add all the other _
info after it.
If line.Contains("[Store Hours]") Then
OutPutLine.Add(line)
'Need to loop through this 7 times (for each day of the week)
'without reading the header again
Dim aryLabelDay() As String = {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}
For intCount = 0 To 6
'even though we're not using the info from the file, calling _
Readline advances the file pointer so that the next iteration _
of the while loop we can finish reading the file.
If Not sr.EndOfStream Then
line = sr.ReadLine
Dim dymTextNameIn As TextBox = DirectCast(Me.Controls("txt" & aryLabelDay(intCount) & "In"), TextBox)
Dim dymDropNameIn As ComboBox = DirectCast(Me.Controls("drp" & aryLabelDay(intCount) & "In"), ComboBox)
Dim dymTextNameOut As TextBox = DirectCast(Me.Controls("txt" & aryLabelDay(intCount) & "Out"), TextBox)
Dim dymDropNameOut As ComboBox = DirectCast(Me.Controls("drp" & aryLabelDay(intCount) & "Out"), ComboBox)
OutPutLine.Add(dymTextNameIn.Text & "," & dymDropNameIn.Text & "," & dymTextNameOut.Text & "," & dymDropNameOut.Text)
End If
Next
Else
'Any line that isn't in that section gets copied as is.
OutPutLine.Add(line)
End If
End While
'Copy all the new info to the same file overwriting the old info.
File.WriteAllLines(objFileName, OutPutLine)
End Sub
On a side note. The Controls collection is indexed by number or name which makes it fairly simple to access the appropriate control just by knowing its name.
Thanks for the help I actually figured it out and this is the final code I used
Private Sub btnSaveHours_Click(sender As System.Object, e As System.EventArgs) Handles btnSaveHours.Click
Dim intOutPutLine As New List(Of String)()
Dim blnSearchString As Boolean
Dim intLineCount As Integer = -1
Dim intLoopCount As Integer
For Each line As String In System.IO.File.ReadAllLines(objFileName)
blnSearchString = line.Contains("[Store Hours]")
If blnSearchString Then
intLineCount = intOutPutLine.Count
line.Remove(0)
intLoopCount = 0
ElseIf intLineCount = intOutPutLine.Count And intLoopCount < 7 Then
line.Length.ToString()
line.Remove(0)
intLoopCount += 1
Else
intOutPutLine.Add(line)
End If
Next
System.IO.File.WriteAllLines(objFileName, intOutPutLine.ToArray())
Dim objFileWrite As New StreamWriter(objFileName, True)
If File.Exists(objFileName) Then
objFileWrite.WriteLine("[Store Hours]")
Dim varMe As Control = Me
Call subConvertFrom12to24Hours(objFileWrite, varMe)
Else
objFileWrite.WriteLine("[Store Hours]")
Dim varMe As Control = Me
Call subConvertFrom12to24Hours(objFileWrite, varMe)
End If
Call btnClear_Click(sender, e)
End Sub