HY! 如何将列表框项目保存到文本文件中,“,”分开?
我的代码:
Using sfd As SaveFileDialog = New SaveFileDialog
With sfd
.FileName = String.Empty
.Filter = "Text|*.txt"
.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
End With
If sfd.ShowDialog = DialogResult.OK Then
Dim logint() As String = Login.Text.Split({Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
Dim passt() As String = Pass.Text.Split({Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
Dim contents As String = String.Empty
For x As Integer = 0 To logint.Length - 1
contents &= String.Format("{1},{2}{0}", Environment.NewLine, logint(x), passt(x))
Next
If contents.Length > 0 Then
contents = contents.Remove(contents.Length - 1)
End If
My.Computer.FileSystem.WriteAllText(sfd.FileName, contents, False)
End If
End Using
如果我单击一个列表框项目,它会工作,但如果我没有,那么项目保存不起作用。
答案 0 :(得分:0)
试试这个:
If sfd.ShowDialog = DialogResult.OK Then
Dim contents As String = String.Empty '***
Dim c As Integer = Login.Items.Count '***
Dim y As Integer '***
For y = 0 To c - 1 '***
Dim logint() As String = Login.Items.Item(y).Split({Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries) '***
Dim passt() As String = Pass.Items.Item(y).Split({Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries) '***
For x As Integer = 0 To logint.Length - 1
contents &= String.Format("{1},{2}{0}", Environment.NewLine, logint(x), passt(x))
Next
If contents.Length > 0 Then
contents = contents.Remove(contents.Length - 1)
End If
Next '***
My.Computer.FileSystem.WriteAllText(sfd.FileName, contents, False)
End If
更改标有'***
答案 1 :(得分:0)
您可以使用一些LINQ在一行中执行此操作:
IO.File.WriteAllLines("file path here",
Enumerable.Range(0, Login.Items.Count).
Select(Function(n) String.Format("{0},{1}",
Login.Items(n),
Pass.Items(n))))