when i want write into a file with visual basic its says he cant becous its already in another procces buts nothings else has op it.
her is my code.
Imports System.IO
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Button1.Visible = False
Label1.Visible = False
pathlocation.Visible = True
Button2.Visible = True
End Sub
Private Sub Label1_Click(sender As Object, e As EventArgs) Handles Label1.Click
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
pathlocation.Visible = False
Button2.Visible = False
End Sub
Public Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
Dim path As String
Dim modsl As String = "/modshop"
Dim config As String = "/config"
Dim configfile As String = "/config.txt"
Dim configwriter As System.IO.StreamWriter
path = pathlocation.Text
path = path + modsl
My.Computer.FileSystem.CreateDirectory(path)
config = path + config
My.Computer.FileSystem.CreateDirectory(config)
configfile = config + configfile
File.Create(configfile)
configwriter = File.AppendText(configfile)
configwriter.Write(path)
configwriter.Close()
Button2.Visible = False
End Sub
Private Sub pathlocation_TextChanged(sender As Object, e As EventArgs) Handles pathlocation.TextChanged
End Sub
End Class
File.Create creates the file and returns a FileStream, thus the following File.AppendText finds the file already opened by yourself and fails
You could simplify a lot your code considering this and the fact that Directory.CreateDirectory method builds all the missing directories in the path passed
Dim path = System.IO.Path.Combine(pathlocation.Text, "modshop")
Dim fullPath = System.IO.Path.Combine(path, "config")
Directory.CreateDirectory(fullPath)
Dim configFile = System.IO.Path.Combine(fullPath, "config.txt")
File.WriteAllText(configFile, path)
Following the logic of your code I have used File.WriteAllText that creates or overwrite the configFile if it exists. If you want to append to an existing file without overwriting its contents then use File.AppendAllText
Related
Here's what error I got while connecting the Access database to my Visual Studio.
I am confused about what to do next.
Public Class main
Const WM_NCHITTEST As Integer = &H84
Const HTCLIENT As Integer = &H1
Const HTCAPTION As Integer = &H2
Private Sub main_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DoubleBuffered = True
Timer1.Start()
Label1.Text = "Locker"
End Sub
Private Sub Timer1_Tick(sender As Object, e As EventArgs) Handles Timer1.Tick
Label1.Location = New Point(Label1.Location.X + 15, Label1.Location.Y)
If (Label1.Location.X >= 330) Then
Timer1.Stop()
Timer2.Start()
End If
End Sub
Private Sub Timer2_Tick(sender As Object, e As EventArgs) Handles Timer2.Tick
DoubleBuffered = True
GroupBox1.Size = New Size(GroupBox1.Size.Width, GroupBox1.Size.Height + 10)
If (GroupBox1.Size.Height >= 298) Then
Timer2.Stop()
End If
End Sub
Protected Overrides Sub WndProc(ByRef m As Message)
Select Case m.Msg
Case WM_NCHITTEST
MyBase.WndProc(m)
If m.Result = IntPtr.op_Explicit(HTCLIENT) Then m.Result = IntPtr.op_Explicit(HTCAPTION)
Case Else
MyBase.WndProc(m)
End Select
End Sub
End Class
Try removing it from Resources from Properties(Alt+Enter). And Re-open it. I think whenever you delete any resource file which is been used by a form then the form designer code can not locate it so try this one also by removing the line of code from Form[Designer].vb (opening in Notepad++).
The error above happens with VS 2017 15.5.2 in a test project while executing the following test. There are binding redirects in the test.vbproj file but nothing for msbuild.
<TestMethod()> Public Sub ElementTypeUnitTestAsync()
Dim RoslynPath As String = Path.Combine(RepoPath, SolutionPartialPath)
Dim MS_Workspace As MSBuildWorkspace = MSBuildWorkspace.Create()
AddHandler MS_Workspace.WorkspaceFailed, Sub(sender As Object, e As WorkspaceDiagnosticEventArgs)
Debug.WriteLine(e.Diagnostic.ToString())
End Sub
Dim NewSolution As Solution = MS_Workspace.OpenSolutionAsync(RoslynPath).Result
End Sub
The whole message is
[Failure] Msbuild failed when processing the file 'C:\Repos\roslyn-master\src\Samples\CSharp\APISampleUnitTests\APISampleUnitTestsCS.csproj' with message: C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets: (1601, 5): The "GetReferenceNearestTargetFrameworkTask" task could not be instantiated from the assembly "C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\Common7\IDE\CommonExtensions\Microsoft\NuGet\NuGet.Build.Tasks.dll". Please verify the task assembly has been built using the same version of the Microsoft.Build.Framework assembly as the one installed on your computer and that your host application is not missing a binding redirect for Microsoft.Build.Framework. Unable to cast object of type 'NuGet.Build.Tasks.GetReferenceNearestTargetFrameworkTask' to type 'Microsoft.Build.Framework.ITask'.
C:\Program Files (x86)\Microsoft Visual Studio\2017\Enterprise\MSBuild\15.0\Bin\Microsoft.Common.CurrentVersion.targets: (1601, 5): The "GetReferenceNearestTargetFrameworkTask" task has been declared or used incorrectly, or failed during construction. Check the spelling of the task name and the assembly name.
This code will allow selection of VS instance if there are more than 1
Imports Microsoft.Build.Locator
Public Class VS_Selector_Dialog1
Private m_instance As VisualStudioInstance = Nothing
Private SelectedRow As Integer = -1
Private visualStudioInstances() As VisualStudioInstance = MSBuildLocator.QueryVisualStudioInstances().ToArray()
Public ReadOnly Property MSBuildInstance As VisualStudioInstance
Get
Return m_instance
End Get
End Property
Private Sub Cancel_Button_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Cancel_Button.Click
DialogResult = DialogResult.Cancel
Close()
End Sub
Private Sub DataGridView1_SelectionChanged(sender As Object, e As EventArgs) Handles DataGridView1.SelectionChanged
m_instance = visualStudioInstances(DataGridView1.CurrentRow.Index)
End Sub
Private Sub OK_Button_Click(ByVal sender As Object, ByVal e As EventArgs) Handles OK_Button.Click
If m_instance Is Nothing Then
Exit Sub
End If
DialogResult = DialogResult.OK
Close()
End Sub
Private Sub VS_Selector_Dialog1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim BestIndex As Integer = -1
Text = "Multiple installs of MSBuild detected please select one:"
Dim InstanceTable As New DataTable
InstanceTable.Columns.Add("InstanceNumber")
InstanceTable.Columns.Add("Edition")
InstanceTable.Columns.Add("Version")
InstanceTable.Columns.Add("MSBuildPath")
For Index As Integer = 0 To visualStudioInstances.Length - 1
If visualStudioInstances(Index).Name.Contains(" Build ") Then
Continue For
End If
BestIndex = Index
Dim rowToAdd As DataRow = InstanceTable.NewRow()
rowToAdd("InstanceNumber") = Index + 1
rowToAdd("Edition") = visualStudioInstances(Index).Name
rowToAdd("Version") = visualStudioInstances(Index).Version
rowToAdd("MSBuildPath") = visualStudioInstances(Index).MSBuildPath
InstanceTable.Rows.Add(rowToAdd)
Next
DataGridView1.DataSource = InstanceTable
If InstanceTable.Rows.Count = 1 Then
m_instance = visualStudioInstances(BestIndex)
DialogResult = DialogResult.OK
Close()
End If
End Sub
End Class
Have the user select the instance, or you get select the "best"
If VS_Selector_Dialog1.ShowDialog(Me) <> DialogResult.OK Then
Stop
End If
Once you have the correct instance MSBuild will work
Console.WriteLine($"Using MSBuild at '{VS_Selector_Dialog1.MSBuildInstance.MSBuildPath}' to load projects.")
' NOTE: Be sure to register an instance with the MSBuildLocator
' before calling MSBuildWorkspace.Create()
' otherwise, MSBuildWorkspace won't MEF compose.
MSBuildLocator.RegisterInstance(VS_Selector_Dialog1.MSBuildInstance)
Using Workspace As MSBuildWorkspace = MSBuildWorkspace.Create()
AddHandler Workspace.WorkspaceFailed, AddressOf MSBuildWorkspaceFailed
Dim currentProject As Project = Workspace.OpenProjectAsync(.FileName).Result
Workspace.LoadMetadataForReferencedProjects = True
If currentProject.HasDocuments Then
For Each document As Document In currentProject.Documents
I have two forms with msflexgrid to display data with datasource from datatable.
I want to drag and drop rows between two form each other. I saw this topic and edited but it doesn't work.
Drag data from DG and other controls to another DG in vb.net
This error:
Please help me!
This is my form1
form1
Code form 1:
Imports C1.Win.C1FlexGrid
Public Class frm1
Private mdt As New DataTable("Test")
Private downHitInfo As C1.Win.C1FlexGrid.HitTestInfo = Nothing
Private Sub frm1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
mdt.Columns.Add("EmplCode")
mdt.Columns.Add("EmplName")
mdt.Rows.Add("012345", "A")
mdt.Rows.Add("012346", "B")
mdt.Rows.Add("012347", "C")
flg1.DataSource = mdt
With flg1
.DragMode = DragModeEnum.Manual
.DropMode = DropModeEnum.Manual
End With
End Sub
Private Sub flg1_MouseDown(sender As Object, e As MouseEventArgs) Handles flg1.MouseDown
Dim view As C1FlexGrid = CType(sender, C1FlexGrid)
Dim hitInfo As C1.Win.C1FlexGrid.HitTestInfo = view.HitTest(e.X, e.Y)
If Not Control.ModifierKeys = Keys.None Then
Exit Sub
End If
If e.Button = MouseButtons.Left Then
downHitInfo = hitInfo
End If
End Sub
Private Sub flg1_MouseMove(sender As Object, e As MouseEventArgs) Handles flg1.MouseMove
Dim view As C1FlexGrid = CType(sender, C1FlexGrid)
If e.Button = MouseButtons.Left And Not downHitInfo Is Nothing Then
Dim dragSize As Size = SystemInformation.DragSize
Dim DragRect As Rectangle = New Rectangle(New Point(Convert.ToInt32(downHitInfo.X - dragSize.Width / 2), _
Convert.ToInt32(downHitInfo.Y - dragSize.Height / 2)), dragSize)
If Not DragRect.Contains(New Point(e.X, e.Y)) Then
'Extract the DataRow
Dim gridRowView As C1.Win.C1FlexGrid.Row = DirectCast(view.Rows(downHitInfo.Row), C1.Win.C1FlexGrid.Row)
'Dim rowView As DataRowView = DirectCast(gridRowView.DataBoundItem, DataRowView)
Dim rowView As DataRowView = DirectCast(gridRowView.DataMap, DataRowView)
'Raise the DragDrop with the extracted DataRow
view.DoDragDrop(rowView.Row, DragDropEffects.Move)
downHitInfo = Nothing
End If
End If
End Sub
Private Sub btn1_Click(sender As Object, e As EventArgs) Handles btn1.Click
Dim lfrm As New frm2()
lfrm.Show()
End Sub
End Class
This is form 2:
Form 2
Code of form 2:
Imports C1.Win.C1FlexGrid
Public Class frm2
Private Sub frm2_Load(sender As Object, e As EventArgs) Handles MyBase.Load
With flg2
.DragMode = DragModeEnum.Manual
.DropMode = DropModeEnum.Manual
End With
End Sub
Private Sub flg2_DragOver(sender As Object, e As DragEventArgs) Handles flg2.DragOver
e.Effect = DragDropEffects.Move
End Sub
Private Sub flg2_DragDrop(sender As Object, e As DragEventArgs) Handles flg2.DragDrop
Dim draggedRow As DataRow = CType(e.Data.GetData(GetType(DataRow)), DataRow)
End Sub
End Class
I created a small app in vb.net for a friend. The problem is that on my PC (W7 64bits) it works great (registry reading / writing) but on my friends PC (W8 64bits) it doesn't work.
It it strange but at the moment he runs my app (it checks the registry on loading) it gives him a "Access to registry denied" error. I tried to run it with admin rights but it doesn't work either.
Here is my code:
Imports Microsoft.Win32
Public Class Form1
Dim planned As Date
Private Sub DateTimePicker1_ValueChanged(sender As Object, e As EventArgs) Handles DateTimePicker1.ValueChanged
End Sub
Private Sub planifier_Click(sender As Object, e As EventArgs) Handles planifier_button.Click
Dim toExecute As String = String.Format("shutdown -s -f -t {0}", 100)
Dim currentDate = System.DateTime.Now
Dim futureDate = DateTimePicker1.Value
Dim difference = futureDate - currentDate
Console.Out.WriteLine(difference)
System.Diagnostics.Process.Start("shutdown", "-s -f -t " & Math.Round(difference.TotalSeconds))
Me.planned = futureDate
saveStgFile(futureDate)
setup()
End Sub
Private Sub Shutdown_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Console.Out.WriteLine(Application.ProductName & " & " & Application.ExecutablePath)
getStgFile()
getPlanned()
setup()
Dim baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)
Startup.Checked = baseKey.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", True).GetValue(Application.ProductName).Equals(Application.ExecutablePath)
End Sub
Private Sub cancel_button_Click(sender As Object, e As EventArgs) Handles cancel_button.Click
System.Diagnostics.Process.Start("shutdown", "-a")
Me.planned = Nothing
saveStgFile(Nothing)
setup()
End Sub
Sub setup()
If Me.planned.Equals(Nothing) Then
cancel_button.Enabled = False
planifier_button.Enabled = True
planifier_button.Text = "Planifier"
Else
cancel_button.Enabled = True
planifier_button.Enabled = False
planifier_button.Text = Me.planned.TimeOfDay.ToString()
End If
End Sub
Function getPlanned() As TimeSpan
Dim stg As String = getStgFile()
Dim fileContent As String = My.Computer.FileSystem.ReadAllText(stg)
Dim timespan As Date
If fileContent = "none" Then
Me.planned = Nothing
ElseIf Date.TryParse(fileContent, timespan) Then
Me.planned = timespan
End If
Return (Me.planned - System.DateTime.Now)
End Function
Function getStgFile() As String
Dim stgFile = System.IO.Path.Combine(My.Computer.FileSystem.SpecialDirectories.MyDocuments, "AutoShutdown")
If My.Computer.FileSystem.DirectoryExists(stgFile) = False Then
FileSystem.MkDir(stgFile)
End If
stgFile = System.IO.Path.Combine(stgFile, "settings.ini")
If My.Computer.FileSystem.FileExists(stgFile) = False Then
My.Computer.FileSystem.WriteAllText(stgFile, "none", False)
End If
Return stgFile
End Function
Sub saveStgFile(planned As Date)
Dim stgFile As String = getStgFile()
Try
If (planned.Equals(Nothing)) Then
My.Computer.FileSystem.WriteAllText(stgFile, "none", False)
Else
My.Computer.FileSystem.WriteAllText(stgFile, planned.ToString(), False)
End If
Catch ex As Exception
Throw ex
End Try
End Sub
Private Sub Startup_CheckedChanged(sender As Object, e As EventArgs) Handles Startup.CheckedChanged
Dim baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64)
If Startup.Checked Then
baseKey.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", True).SetValue(Application.ProductName, Application.ExecutablePath)
Console.Out.WriteLine("Add to startup")
Else
baseKey.OpenSubKey("SOFTWARE\Microsoft\Windows\CurrentVersion\Run", True).DeleteValue(Application.ProductName)
Console.Out.WriteLine("Remove from startup")
End If
End Sub
End Class
The following code will extract files from one Folder and Place them another as you can see. But I am trying to delete the files that have not been modified in the past 3 months, and it does not delete any files at all.
Code:
Imports System.IO
Public Class frmExtractionator
Dim txtFiles1 As Control
Private Sub btnStart_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStart.Click
Dim sourceDirectory As String = "E:\CopierFolderforTestDriveCapstone"
Dim archiveDirectory As String = "E:\FilesExtracted"
Try
Dim txtFiles = Directory.EnumerateFiles(sourceDirectory)
If (Not System.IO.Directory.Exists(archiveDirectory)) Then
System.IO.Directory.CreateDirectory(archiveDirectory)
End If
For Each currentFileLoc As String In txtFiles
Dim fileName = currentFileLoc.Substring(sourceDirectory.Length + 1)
File.Move(currentFileLoc, Path.Combine(archiveDirectory, fileName))
Try
Dim di As DirectoryInfo = New DirectoryInfo(sourceDirectory)
Dim fi As FileInfo() = di.GetFiles()
For Each currentFile As FileInfo In fi
File.Move(currentFile.FullName, Path.Combine(archiveDirectory, currentFile.Name))
Dim dt As DateTime = currentFile.LastWriteTime
' Add 3 months to the last write and check if it is less than today '
If dt.AddMonths(3) < DateTime.Today Then
File.Delete(currentFile.FullName)
End If
Next
Catch eT As Exception
Console.WriteLine(eT.Message)
End Try
Next
Catch eT As Exception
Console.WriteLine(eT.Message)
End Try
End Sub
End Class