I need a function to complete the following tasks:
Check if a folder exists (via its name) - if not then, create it.
Upload a file into the directory.
I tried with the following code, but it does not seem to check and create the directory:
Dim request As System.Net.FtpWebRequest = DirectCast(System.Net.FtpWebRequest.Create("HOST"), System.Net.FtpWebRequest)
request.Credentials = New System.Net.NetworkCredential("uase", "pass")
request.Method = System.Net.WebRequestMethods.Ftp.UploadFile
Dim file() As Byte = System.IO.File.ReadAllBytes("C:\Users\Nini\Desktop\10ebd0d.png")
Dim str As System.IO.Stream = request.GetRequestStream()
str.Write(file, 0, file.Length)
str.Close()
str.Dispose()
1.Check if a folder exists (via its name) - if not then, create it.
I'll admit that this is not the most robust or elegant solution but I was OK with something 'quick and dirty' for the occasional one-off need that I have for this.
Dim request As FtpWebRequest = FtpWebRequest.Create("ftp://myftp/parentfolder")
Dim creds As NetworkCredential = New NetworkCredential("user", "pwd")
request.Credentials = creds
Dim resp As FtpWebResponse = Nothing
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails
request.KeepAlive = True
Using resp
resp = request.GetResponse()
Dim sr As StreamReader = New StreamReader(resp.GetResponseStream(), System.Text.Encoding.ASCII)
Dim s As String = sr.ReadToEnd()
If Not s.Contains("newfolder") Then
request = FtpWebRequest.Create("ftp://myftp/parentfolder/newfolder")
request.Credentials = creds
request.Method = WebRequestMethods.Ftp.MakeDirectory
resp = request.GetResponse()
Console.WriteLine(resp.StatusCode & "Created")
Else
Console.WriteLine("Directory already exists")
End If
Console.ReadLine()
End Using
You could use the FTPClient library for .NET
I've did an helper Class to manage the library (but is easy as is provided there is no need to use an helper Class)
The methods that you're interested to are DirectoryExists, CreateDirectory, and UploadFile
This is an example usage:
Public Class Form1
Private WithEvents UploadClient As New System.Net.WebClient()
Private WithEvents DownloadClient As New System.Net.WebClient()
Private ftp As New FTP("ftpsite", "username", "password")
Private Sub Test() Handles MyBase.Shown
ftp.Connect()
ftp.CreateDirectory("/DirectoryName", True)
ftp.UploadFile(UploadClient, "C:\File.txt", "/DirectoryName/NewFile.txt", False)
ftp.DownloadFile(DownloadClient, "/DirectoryName/NewFile.txt", "c:\DownloadedFile.txt", True)
End Sub
Private Sub Client_UploadProgress(sender As System.Net.WebClient, e As System.Net.UploadProgressChangedEventArgs) _
Handles UploadClient.UploadProgressChanged
Label_Upload.Text = e.ProgressPercentage & "%"
End Sub
Private Sub Client_UploadCompleted(sender As System.Net.WebClient, e As System.Net.UploadFileCompletedEventArgs) _
Handles UploadClient.UploadFileCompleted
Label_UploadCompleted.Text = e.Result.ToString
End Sub
Private Sub Client_DownloadProgress(sender As System.Net.WebClient, e As System.Net.DownloadProgressChangedEventArgs) _
Handles DownloadClient.DownloadProgressChanged
Label_Download.Text = e.ProgressPercentage & "%"
End Sub
Private Sub Client_DownloadCompleted(sender As System.Net.WebClient, e As System.ComponentModel.AsyncCompletedEventArgs) _
Handles DownloadClient.DownloadFileCompleted
Label_DownloadCompleted.Text = "Done!"
End Sub
End Class
The Helper Class:
Imports System.Net
Imports System.Net.FtpClient
Imports System.Net.FtpClient.Extensions
#Region " FTPClient Helper "
' [ FTPClient Helper ]
'
' // By Elektro
Public Class FTP
#Region " Variables "
Private conn As New FtpClient
''' <summary>
''' The FTP site.
''' </summary>
Private Property host As String = String.Empty
''' <summary>
''' The user name.
''' </summary>
Private Property user As String = String.Empty
''' <summary>
''' The user password.
''' </summary>
Private Property pass As String = String.Empty
' Friend m_reset As New ManualResetEvent(False) ' Use it for CallBacks
#End Region
#Region " Constructor "
''' <summary>
''' .
''' </summary>
''' <param name="host">Indicates the ftp site.</param>
''' <param name="user">Indicates the username.</param>
''' <param name="pass">Indicates the password.</param>
Public Sub New(ByVal host As String,
ByVal user As String,
ByVal pass As String)
If Not host.ToLower.StartsWith("ftp://") Then
Me.host = "ftp://" & host
Else
Me.host = host
End If
If Me.host.Last = "/" Then
Me.host = Me.host.Remove(Me.host.Length - 1)
End If
Me.user = user
Me.pass = pass
With conn
.Host = If(host.Last = "/", host.Remove(host.Length - 1), host)
.Credentials = New NetworkCredential(Me.user, Me.pass)
End With
End Sub
#End Region
#Region " Public Methods "
''' <summary>
''' Connects to server.
''' </summary>
Public Sub Connect()
conn.Connect()
End Sub
''' <summary>
''' Disconnects from server.
''' </summary>
Public Sub Disconnect()
conn.Disconnect()
End Sub
''' <summary>
''' Creates a directory on server.
''' </summary>
''' <param name="directorypath">Indicates the ftp directory path.</param>
''' <param name="force">Try to force all non-existant pieces of the path to be created.</param>
Public Sub CreateDirectory(ByVal directorypath As String, ByVal force As Boolean)
conn.CreateDirectory(directorypath, force)
End Sub
''' <summary>
''' Creates a directory on server.
''' </summary>
''' <param name="directorypath">Indicates the ftp directory path.</param>
''' <param name="force">Try to force all non-existant pieces of the path to be created.</param>
''' <param name="FtpListOption">Options that dictate how a list is performed ans what information is gathered.</param>
Public Sub DeleteDirectory(ByVal directorypath As String,
ByVal force As Boolean,
Optional ByVal FtpListOption As FtpListOption =
FtpListOption.AllFiles Or FtpListOption.ForceList)
' Remove the directory and all objects beneath it. The last parameter
' forces System.Net.FtpClient to use LIST -a for getting a list of objects
' beneath the specified directory.
conn.DeleteDirectory(directorypath, force, FtpListOption)
End Sub
''' <summary>
''' Deletes a file on server.
''' </summary>
''' <param name="filepath">Indicates the ftp file path.</param>
Public Sub DeleteFile(ByVal filepath As String)
conn.DeleteFile(filepath)
End Sub
''' <summary>
''' Checks if a directory exist on server.
''' </summary>
''' <param name="directorypath">Indicates the ftp directory path.</param>
Public Function DirectoryExists(ByVal directorypath As String) As Boolean
Return conn.DirectoryExists(directorypath)
End Function
''' <summary>
''' Executes a command on server.
''' </summary>
''' <param name="command">Indicates the command to execute on the server.</param>
''' <returns>Returns an object containing the server reply information.</returns>
Public Function Execute(ByVal command As String) As FtpReply
Return (InlineAssignHelper(New FtpReply, conn.Execute(command)))
End Function
''' <summary>
''' Tries to execute a command on server.
''' </summary>
''' <param name="command">Indicates the command to execute on the server.</param>
''' <returns>Returns TRUE if command execution successfull, otherwise returns False.</returns>
Public Function TryExecute(ByVal command As String) As Boolean
Dim reply As FtpReply = Nothing
Return (InlineAssignHelper(reply, conn.Execute(command))).Success
End Function
''' <summary>
''' Checks if a file exist on server.
''' </summary>
''' <param name="filepath">Indicates the ftp file path.</param>
''' <param name="FtpListOption">Options that dictate how a list is performed ans what information is gathered.</param>
Public Function FileExists(ByVal filepath As String,
Optional ByVal FtpListOption As FtpListOption =
FtpListOption.AllFiles Or FtpListOption.ForceList) As Boolean
' The last parameter forces System.Net.FtpClient to use LIST -a
' for getting a list of objects in the parent directory.
Return conn.FileExists(filepath, FtpListOption)
End Function
''' <summary>
''' Retrieves a checksum of the given file
''' using a checksumming method that the server supports, if any.
''' The algorithm used goes in this order:
''' 1. HASH command (server preferred algorithm).
''' 2. MD5 / XMD5 commands
''' 3. XSHA1 command
''' 4. XSHA256 command
''' 5. XSHA512 command
''' 6. XCRC command
''' </summary>
''' <param name="filepath">Indicates the ftp file path.</param>
Public Function GetChecksum(ByVal filepath As String) As FtpHash
Return conn.GetChecksum(filepath)
End Function
''' <summary>
''' Gets the checksum of file on server and compare it with the checksum of local file.
''' </summary>
''' <param name="filepath">Indicates the ftp file path.</param>
''' <param name="localfilepath">Indicates the local disk file path.</param>
''' <param name="algorithm">Indicates the algorithm that should be used to verify checksums.</param>
''' <returns>Returns TRUE if both checksums are equal, otherwise returns False.</returns>
Public Function VerifyChecksum(ByVal filepath As String,
ByVal localfilepath As String,
ByVal algorithm As FtpHashAlgorithm) As Boolean
Dim hash As FtpHash = Nothing
hash = conn.GetChecksum(filepath)
' Make sure it returned a, to the best of our knowledge, valid hash object.
' The commands for retrieving checksums are
' non-standard extensions to the protocol so we have to
' presume that the response was in a format understood by
' System.Net.FtpClient and parsed correctly.
'
' In addition, there is no built-in support for verifying CRC hashes.
' You will need to write you own or use a third-party solution.
If hash.IsValid AndAlso hash.Algorithm <> algorithm Then
Return hash.Verify(localfilepath)
Else
Return Nothing
End If
End Function
''' <summary>
''' Gets the size of file.
''' </summary>
''' <param name="filepath">Indicates the ftp file path.</param>
Public Function GetFileSize(ByVal filepath As String) As Long
Return conn.GetFileSize(filepath)
End Function
''' <summary>
''' Gets the currently HASH algorithm used for the HASH command on server.
''' </summary>
Public Function GetHashAlgorithm() As FtpHashAlgorithm
Return conn.GetHashAlgorithm()
End Function
''' <summary>
''' Gets the modified time of file.
''' </summary>
''' <param name="filepath">Indicates the ftp file path.</param>
Public Function GetModifiedTime(ByVal filepath As String) As Date
Return conn.GetModifiedTime(filepath)
End Function
''' <summary>
''' Returns a file/directory listing using the NLST command.
''' </summary>
''' <param name="directorypath">Indicates the ftp file path.</param>
Public Function GetNameListing(ByVal directorypath As String) As String()
Return conn.GetNameListing(directorypath)
End Function
''' <summary>
''' Gets the current working directory on server.
''' </summary>
Public Function GetWorkingDirectory() As String
Return conn.GetWorkingDirectory()
End Function
''' <summary>
''' Opens the specified file to be appended to...
''' </summary>
''' <param name="filepath">Indicates the ftp file path.</param>
Public Function OpenAppend(ByVal filepath As String) As IO.Stream
Return conn.OpenAppend(filepath)
End Function
''' <summary>
''' Opens the specified file for reading.
''' </summary>
''' <param name="filepath">Indicates the ftp file path.</param>
Public Function OpenRead(ByVal filepath As String) As IO.Stream
Return conn.OpenRead(filepath)
End Function
''' <summary>
''' Opens the specified file for writing.
''' </summary>
''' <param name="filepath">Indicates the ftp file path.</param>
Public Function OpenWrite(ByVal filepath As String) As IO.Stream
Return conn.OpenWrite(filepath)
End Function
''' <summary>
''' Rename a file on the server.
''' </summary>
''' <param name="filepath">Indicates the ftp file path.</param>
''' <param name="newfilepath">Indicates the new ftp file path.</param>
Public Sub RenameFile(ByVal filepath As String, ByVal newfilepath As String)
If conn.FileExists(filepath) Then
conn.Rename(filepath, newfilepath)
Else
Throw New Exception(filepath & " File does not exist on server.")
End If
End Sub
''' <summary>
''' Rename a directory on the server.
''' </summary>
''' <param name="directorypath">Indicates the ftp file path.</param>
''' <param name="newdirectorypath">Indicates the new ftp file path.</param>
Public Sub RenameDirectory(ByVal directorypath As String, ByVal newdirectorypath As String)
If conn.DirectoryExists(directorypath) Then
conn.Rename(directorypath, newdirectorypath)
Else
Throw New Exception(directorypath & " Directory does not exist on server.")
End If
End Sub
''' <summary>
''' Tells the server wich hash algorithm to use for the HASH command.
''' </summary>
''' <param name="algorithm">Indicates the HASH algorithm.</param>
Public Function SetHashAlgorithm(ByVal algorithm As FtpHashAlgorithm) As Boolean
If conn.HashAlgorithms.HasFlag(algorithm) Then
conn.SetHashAlgorithm(algorithm)
Return True
Else
Return False
End If
End Function
''' <summary>
''' Sets the working directory on the server.
''' </summary>
''' <param name="directorypath">Indicates the ftp directory path.</param>
Public Sub SetWorkingDirectory(ByVal directorypath As String)
conn.SetWorkingDirectory(directorypath)
End Sub
''' <summary>
''' Gets a directory list on the specified path.
''' </summary>
''' <param name="directorypath">Indicates the ftp directory path.</param>
''' <param name="FtpListOption">Options that dictate how a list is performed ans what information is gathered.</param>
Public Function GetDirectories(ByVal directorypath As String,
Optional ByVal FtpListOption As FtpListOption =
FtpListOption.AllFiles) As FtpListItem()
Return conn.GetListing(directorypath, FtpListOption).
Where(Function(item) item.Type = FtpFileSystemObjectType.Directory)
End Function
''' <summary>
''' Gets a file list on the specified path.
''' </summary>
''' <param name="directorypath">Indicates the ftp directory path.</param>
''' <param name="FtpListOption">Options that dictate how a list is performed ans what information is gathered.</param>
Public Function GetFiles(ByVal directorypath As String,
Optional ByVal FtpListOption As FtpListOption =
FtpListOption.AllFiles) As FtpListItem()
Return conn.GetListing(directorypath, FtpListOption).
Where(Function(item) item.Type = FtpFileSystemObjectType.File)
End Function
''' <summary>
''' Gets a link list on the specified path.
''' </summary>
''' <param name="directorypath">Indicates the ftp directory path.</param>
''' <param name="FtpListOption">Options that dictate how a list is performed ans what information is gathered.</param>
Public Function GetLinks(ByVal directorypath As String,
Optional ByVal FtpListOption As FtpListOption =
FtpListOption.AllFiles) As FtpListItem()
Return conn.GetListing(directorypath, FtpListOption).
Where(Function(item) item.Type = FtpFileSystemObjectType.Link)
End Function
''' <summary>
''' Gets a file/folder list on the specified path.
''' </summary>
''' <param name="directorypath">Indicates the ftp directory path.</param>
''' <param name="FtpListOption">Options that dictate how a list is performed ans what information is gathered.</param>
Public Function GetListing(ByVal directorypath As String,
Optional ByVal FtpListOption As FtpListOption =
FtpListOption.AllFiles) As FtpListItem()
Return conn.GetListing(directorypath, FtpListOption)
End Function
''' <summary>
''' Log to a console window
''' </summary>
Public Sub LogToConsole()
FtpTrace.AddListener(New ConsoleTraceListener())
' now use System.Net.FtpCLient as usual and the server transactions
' will be written to the Console window.
End Sub
''' <summary>
''' Log to a text file
''' </summary>
''' <param name="filepath">Indicates the file where to save the log.</param>
Public Sub LogToFile(ByVal filepath As String)
FtpTrace.AddListener(New TextWriterTraceListener(filepath))
' now use System.Net.FtpCLient as usual and the server transactions
' will be written to the specified log file.
End Sub
''' <summary>
''' Uploads a file to FTP.
''' </summary>
''' <param name="UploadClient">Indicates the WebClient object to upload the file.</param>
''' <param name="filepath">Indicates the ftp fle path.</param>
''' <param name="localfilepath">Specifies the local path where to save the downloaded file.</param>
''' <param name="Asynchronous">Indicates whether the download should be an Asynchronous operation,
''' to raise WebClient events.</param>
Public Sub UploadFile(ByRef UploadClient As WebClient,
ByVal localfilepath As String,
Optional ByVal filepath As String = Nothing,
Optional ByVal Asynchronous As Boolean = False)
If filepath Is Nothing Then
filepath = Me.host & "/" & New IO.FileInfo(localfilepath).Name
ElseIf filepath.StartsWith("/") Then
filepath = Me.host & filepath
Else
filepath = Me.host & "/" & filepath
End If
With UploadClient
.Credentials = New NetworkCredential(Me.user, Me.pass)
If Asynchronous Then
.UploadFileAsync(New Uri(filepath), "STOR", localfilepath)
Else
.UploadFile(New Uri(filepath), "STOR", localfilepath)
End If
End With
End Sub
''' <summary>
''' Downloads a file from FTP.
''' </summary>
''' <param name="DownloadClient">Indicates the WebClient object to download the file.</param>
''' <param name="filepath">Indicates the ftp fle path.</param>
''' <param name="localfilepath">Specifies the local path where to save the downloaded file.</param>
''' <param name="Asynchronous">Indicates whether the download should be an Asynchronous operation,
''' to raise WebClient events.</param>
Public Sub DownloadFile(ByRef DownloadClient As WebClient,
ByVal filepath As String,
ByVal localfilepath As String,
Optional ByVal Asynchronous As Boolean = False)
If filepath.StartsWith("/") Then
filepath = Me.host & filepath
Else
filepath = Me.host & "/" & filepath
End If
With DownloadClient
.Credentials = New NetworkCredential(Me.user, Me.pass)
If Asynchronous Then
.DownloadFileAsync(New Uri(filepath), localfilepath)
Else
.DownloadFile(New Uri(filepath), localfilepath)
End If
End With
End Sub
#End Region
#Region " Miscellaneous methods "
Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, value As T) As T
target = value
Return value
End Function
#End Region
End Class
#End Region
Related
As the title says I would like to save variables in a .txt file or something similar. (not XML)I've tried My.Settings and I'd like a more portable solution.
Format being something like this:
[config]<br>
StartPath=C:\Users<br>
FormColour=Black
From your question it looks you are thinking about sort of configuration (or similar) file looking like .ini file in older Windows versions. Such a file has one or more [sections] with multiple name=value pairs in each. If this is your case, please take a look here:
Reading/writing an INI file
If you are going to store data which suit multi-level structure better than simple flat structure you show in the sample and you do not like XML for this purpose, you might consider for example JSON (available natively in .NET since version 3.5) or YAML. Their libraries are freely available for .NET.
For a portable solution you can use my INI File Manager which is really easy and secure to use.
#Region " INI File Manager " ' By Elektro
Public Class INIFileManager
#Region " Members "
#Region " Properties "
''' <summary>
''' Indicates the initialization file path.
''' </summary>
Public Shared Property FilePath As String =
IO.Path.Combine(Application.StartupPath, Process.GetCurrentProcess().ProcessName & ".ini")
#End Region
#Region " Variables "
''' <summary>
''' Stores the initialization file content.
''' </summary>
Private Shared Content As New List(Of String)
''' <summary>
''' Stores the INI section names.
''' </summary>
Private Shared SectionNames As String() = {String.Empty}
''' <summary>
''' Indicates the start element index of a section name.
''' </summary>
Private Shared SectionStartIndex As Integer = -1
''' <summary>
''' Indicates the end element index of a section name.
''' </summary>
Private Shared SectionEndIndex As Integer = -1
''' <summary>
''' Stores a single sorted section block with their keys and values.
''' </summary>
Private Shared SortedSection As New List(Of String)
''' <summary>
''' Stores all the sorted section blocks with their keys and values.
''' </summary>
Private Shared SortedSections As New List(Of String)
''' <summary>
''' Indicates the INI element index that contains the Key and value.
''' </summary>
Private Shared KeyIndex As Integer = -1
''' <summary>
''' Indicates the culture to compare the strings.
''' </summary>
Private Shared ReadOnly CompareMode As StringComparison = StringComparison.InvariantCultureIgnoreCase
#End Region
#Region " Exceptions "
''' <summary>
''' Exception is thrown when a section name parameter has invalid format.
''' </summary>
Private Class SectionNameInvalidFormatException
Inherits Exception
Public Sub New()
MyBase.New("Section name parameter has invalid format." &
Environment.NewLine &
"The rigth syntax is: [SectionName]")
End Sub
Public Sub New(message As String)
MyBase.New(message)
End Sub
Public Sub New(message As String, inner As Exception)
MyBase.New(message, inner)
End Sub
End Class
#End Region
#End Region
#Region " Methods "
<System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)>
Private Shadows Sub ReferenceEquals()
End Sub
<System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)>
Private Shadows Sub Equals()
End Sub
Public Class [File]
<System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)>
Private Shadows Sub ReferenceEquals()
End Sub
<System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)>
Private Shadows Sub Equals()
End Sub
''' <summary>
''' Checks whether the initialization file exist.
''' </summary>
''' <returns>True if initialization file exist, otherwise False.</returns>
Public Shared Function Exist() As Boolean
Return IO.File.Exists(FilePath)
End Function
''' <summary>
''' Creates the initialization file.
''' If the file already exist it would be replaced.
''' </summary>
''' <param name="Encoding">The Text encoding to write the initialization file.</param>
''' <returns>True if the operation success, otherwise False.</returns>
Public Shared Function Create(Optional ByVal Encoding As System.Text.Encoding = Nothing) As Boolean
Try
IO.File.WriteAllText(FilePath,
String.Empty,
If(Encoding Is Nothing, System.Text.Encoding.Default, Encoding))
Catch ex As Exception
Throw
Return False
End Try
Return True
End Function
''' <summary>
''' Deletes the initialization file.
''' </summary>
''' <returns>True if the operation success, otherwise False.</returns>
Public Shared Function Delete() As Boolean
If Not [File].Exist Then Return False
Try
IO.File.Delete(FilePath)
Catch ex As Exception
Throw
Return False
End Try
Content = Nothing
Return True
End Function
''' <summary>
''' Returns the initialization file content.
''' </summary>
''' <param name="Encoding">The Text encoding to read the initialization file.</param>
Public Shared Function [Get](Optional ByVal Encoding As System.Text.Encoding = Nothing) As List(Of String)
Content = IO.File.ReadAllLines(FilePath,
If(Encoding Is Nothing, System.Text.Encoding.Default, Encoding)).ToList()
Return Content
End Function
''' <summary>
''' Sort the initialization file content by the Key names.
''' If the initialization file contains sections then the sections are sorted by their names also.
''' </summary>
''' <param name="RemoveEmptyLines">Remove empty lines.</param>
''' <param name="Encoding">The Text encoding to read the initialization file.</param>
''' <returns>True if the operation success, otherwise False.</returns>
Public Shared Function Sort(Optional ByVal RemoveEmptyLines As Boolean = False,
Optional ByVal Encoding As System.Text.Encoding = Nothing) As Boolean
If Not [File].Exist() Then Return False
[File].[Get](Encoding)
Select Case Section.Has(Encoding)
Case True ' initialization file contains at least one Section.
SortedSection.Clear()
SortedSections.Clear()
Section.GetNames(Encoding) ' Get the (sorted) section names
For Each name As String In SectionNames
SortedSection = Section.[Get](name, Encoding) ' Get the single section lines.
If RemoveEmptyLines Then ' Remove empty lines.
SortedSection = SortedSection.Where(Function(line) _
Not String.IsNullOrEmpty(line) AndAlso
Not String.IsNullOrWhiteSpace(line)).ToList
End If
SortedSection.Sort() ' Sort the single section keys.
SortedSections.Add(name) ' Add the section name to the sorted sections list.
SortedSections.AddRange(SortedSection) ' Add the single section to the sorted sections list.
Next name
Content = SortedSections
Case False ' initialization file doesn't contains any Section.
Content.Sort()
If RemoveEmptyLines Then
Content = Content.Where(Function(line) _
Not String.IsNullOrEmpty(line) AndAlso
Not String.IsNullOrWhiteSpace(line)).ToList
End If
End Select ' Section.Has()
' Save changes.
Return [File].Write(Content, Encoding)
End Function
''' <summary>
''' Writes a new initialization file with the specified text content..
''' </summary>
''' <param name="Content">Indicates the text content to write in the initialization file.</param>
''' <param name="Encoding">The Text encoding to read the initialization file.</param>
''' <returns>True if the operation success, otherwise False.</returns>
Public Shared Function Write(ByVal Content As List(Of String),
Optional ByVal Encoding As System.Text.Encoding = Nothing) As Boolean
Try
IO.File.WriteAllLines(FilePath,
Content,
If(Encoding Is Nothing, System.Text.Encoding.Default, Encoding))
Catch ex As Exception
Throw
Return False
End Try
Return True
End Function
End Class
Public Class [Key]
<System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)>
Private Shadows Sub ReferenceEquals()
End Sub
<System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)>
Private Shadows Sub Equals()
End Sub
''' <summary>
''' Return a value indicating whether a key name exist or not.
''' </summary>
''' <param name="KeyName">Indicates the key name that contains the value to modify.</param>
''' <param name="SectionName">Indicates the Section name where to find the key name.</param>
''' <param name="Encoding">The Text encoding to write the initialization file.</param>
''' <returns>True if the key name exist, otherwise False.</returns>
Public Shared Function Exist(ByVal KeyName As String,
Optional ByVal SectionName As String = Nothing,
Optional ByVal Encoding As System.Text.Encoding = Nothing) As Boolean
If Not [File].Exist() Then Return False
[File].[Get](Encoding)
[Key].GetIndex(KeyName, SectionName)
Select Case SectionName Is Nothing
Case True
Return Convert.ToBoolean(Not KeyIndex)
Case Else
Return Convert.ToBoolean(Not (KeyIndex + SectionStartIndex))
End Select
End Function
''' <summary>
''' Set the value of an existing key name.
'''
''' If the initialization file doesn't exists, or else the Key doesn't exist,
''' or else the Section parameter is not specified and the key name doesn't exist;
''' then the 'key=value' is appended to the end of the initialization file.
'''
''' if the specified Section name exist but the Key name doesn't exist,
''' then the 'key=value' is appended to the end of the Section.
'''
''' </summary>
''' <param name="KeyName">Indicates the key name that contains the value to modify.</param>
''' <param name="Value">Indicates the new value.</param>
''' <param name="SectionName">Indicates the Section name where to find the key name.</param>
Public Shared Function [Set](ByVal KeyName As String,
ByVal Value As String,
Optional ByVal SectionName As String = Nothing,
Optional ByVal Encoding As System.Text.Encoding = Nothing) As Boolean
If Not [File].Exist() Then [File].Create()
[File].[Get](Encoding)
[Key].GetIndex(KeyName, SectionName)
' If KeyName is not found and indicated Section is found, then...
If KeyIndex = -1 AndAlso SectionEndIndex <> -1 Then
' If section EndIndex is the last line of file, then...
If SectionEndIndex = Content.Count Then
Content(Content.Count - 1) = Content(Content.Count - 1) &
Environment.NewLine &
String.Format("{0}={1}", KeyName, Value)
Else ' If not section EndIndex is the last line of file, then...
Content(SectionEndIndex) = String.Format("{0}={1}", KeyName, Value) &
Environment.NewLine &
Content(SectionEndIndex)
End If
' If KeyName is found then...
ElseIf KeyIndex <> -1 Then
Content(KeyIndex) = String.Format("{0}={1}", KeyName, Value)
' If KeyName is not found and Section parameter is passed. then...
ElseIf KeyIndex = -1 AndAlso SectionName IsNot Nothing Then
Content.Add(SectionName)
Content.Add(String.Format("{0}={1}", KeyName, Value))
' If KeyName is not found, then...
ElseIf KeyIndex = -1 Then
Content.Add(String.Format("{0}={1}", KeyName, Value))
End If
' Save changes.
Return [File].Write(Content, Encoding)
End Function
''' <summary>
''' Get the value of an existing key name.
''' If the initialization file or else the Key doesn't exist then a 'Nothing' object is returned.
''' </summary>
''' <param name="KeyName">Indicates the key name to retrieve their value.</param>
''' <param name="DefaultValue">Indicates a default value to return if the key name is not found.</param>
''' <param name="SectionName">Indicates the Section name where to find the key name.</param>
Public Shared Function [Get](ByVal KeyName As String,
Optional ByVal DefaultValue As Object = Nothing,
Optional ByVal SectionName As String = Nothing,
Optional ByVal Encoding As System.Text.Encoding = Nothing) As Object
If Not [File].Exist() Then Return DefaultValue
[File].[Get](Encoding)
[Key].GetIndex(KeyName, SectionName)
Select Case KeyIndex
Case Is <> -1 ' KeyName found.
Return Content(KeyIndex).Substring(Content(KeyIndex).IndexOf("=") + 1)
Case Else ' KeyName not found.
Return DefaultValue
End Select
End Function
''' <summary>
''' Returns the initialization file line index of the key name.
''' </summary>
''' <param name="KeyName">Indicates the Key name to retrieve their value.</param>
''' <param name="SectionName">Indicates the Section name where to find the key name.</param>
Private Shared Sub GetIndex(ByVal KeyName As String,
Optional ByVal SectionName As String = Nothing,
Optional ByVal Encoding As System.Text.Encoding = Nothing)
If Content Is Nothing Then [File].Get(Encoding)
' Reset the INI index elements to negative values.
KeyIndex = -1
SectionStartIndex = -1
SectionEndIndex = -1
If SectionName IsNot Nothing AndAlso Not SectionName Like "[[]?*[]]" Then
Throw New SectionNameInvalidFormatException
Exit Sub
End If
' Locate the KeyName and set their element index.
' If the KeyName is not found then the value is set to "-1" to return an specified default value.
Select Case String.IsNullOrEmpty(SectionName)
Case True ' Any SectionName parameter is specified.
KeyIndex = Content.FindIndex(Function(line) line.StartsWith(String.Format("{0}=", KeyName),
StringComparison.InvariantCultureIgnoreCase))
Case False ' SectionName parameter is specified.
Select Case Section.Has(Encoding)
Case True ' INI contains at least one Section.
SectionStartIndex = Content.FindIndex(Function(line) line.Trim.Equals(SectionName.Trim, CompareMode))
If SectionStartIndex = -1 Then ' Section doesn't exist.
Exit Sub
End If
SectionEndIndex = Content.FindIndex(SectionStartIndex + 1, Function(line) line.Trim Like "[[]?*[]]")
If SectionEndIndex = -1 Then
' This fixes the value if the section is at the end of file.
SectionEndIndex = Content.Count
End If
KeyIndex = Content.FindIndex(SectionStartIndex, SectionEndIndex - SectionStartIndex,
Function(line) line.StartsWith(String.Format("{0}=", KeyName),
StringComparison.InvariantCultureIgnoreCase))
Case False ' INI doesn't contains Sections.
GetIndex(KeyName, , Encoding)
End Select ' Section.Has()
End Select ' String.IsNullOrEmpty(SectionName)
End Sub
''' <summary>
''' Remove an existing key name.
''' </summary>
''' <param name="KeyName">Indicates the key name to retrieve their value.</param>
''' <param name="SectionName">Indicates the Section name where to find the key name.</param>
''' <param name="Encoding">The Text encoding to read the initialization file.</param>
Public Shared Function Remove(ByVal KeyName As String,
Optional ByVal SectionName As String = Nothing,
Optional ByVal Encoding As System.Text.Encoding = Nothing) As Boolean
If Not [File].Exist() Then Return False
[File].[Get](Encoding)
[Key].GetIndex(KeyName, SectionName)
Select Case KeyIndex
Case Is <> -1 ' Key found.
' Remove the element containing the key name.
Content.RemoveAt(KeyIndex)
' Save changes.
Return [File].Write(Content, Encoding)
Case Else ' KeyName not found.
Return False
End Select
End Function
End Class
Public Class Section
<System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)>
Private Shadows Sub ReferenceEquals()
End Sub
<System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)>
Private Shadows Sub Equals()
End Sub
''' <summary>
''' Adds a new section at bottom of the initialization file.
''' </summary>
''' <param name="SectionName">Indicates the Section name to add.</param>
''' <param name="Encoding">The Text encoding to read the initialization file.</param>
Public Shared Function Add(Optional ByVal SectionName As String = Nothing,
Optional ByVal Encoding As System.Text.Encoding = Nothing) As Boolean
If Not [File].Exist() Then [File].Create()
If Not SectionName Like "[[]?*[]]" Then
Throw New SectionNameInvalidFormatException
Exit Function
End If
[File].[Get](Encoding)
Select Case Section.GetNames(Encoding).Where(Function(line) line.Trim.Equals(SectionName.Trim, CompareMode)).Any
Case False ' Any of the existing Section names is equal to given section name.
' Add the new section name.
Content.Add(SectionName)
' Save changes.
Return [File].Write(Content, Encoding)
Case Else ' An existing Section name is equal to given section name.
Return False
End Select
End Function
''' <summary>
''' Returns all the keys and values of an existing Section Name.
''' </summary>
''' <param name="SectionName">Indicates the section name where to retrieve their keynames and values.</param>
Public Shared Function [Get](ByVal SectionName As String,
Optional ByVal Encoding As System.Text.Encoding = Nothing) As List(Of String)
If Content Is Nothing Then [File].Get(Encoding)
SectionStartIndex = Content.FindIndex(Function(line) line.Trim.Equals(SectionName.Trim, CompareMode))
SectionEndIndex = Content.FindIndex(SectionStartIndex + 1, Function(line) line.Trim Like "[[]?*[]]")
If SectionEndIndex = -1 Then
SectionEndIndex = Content.Count ' This fixes the value if the section is at the end of file.
End If
Return Content.GetRange(SectionStartIndex, SectionEndIndex - SectionStartIndex).Skip(1).ToList
End Function
''' <summary>
''' Returns all the section names of the initialization file.
''' </summary>
Public Shared Function GetNames(Optional ByVal Encoding As System.Text.Encoding = Nothing) As String()
If Content Is Nothing Then [File].Get(Encoding)
' Get the Section names.
SectionNames = (From line In Content Where line.Trim Like "[[]?*[]]").ToArray
' Sort the Section names.
If SectionNames.Count <> 0 Then Array.Sort(SectionNames)
' Return the Section names.
Return SectionNames
End Function
''' <summary>
''' Gets a value indicating whether the initialization file contains at least one Section.
''' </summary>
''' <param name="Encoding">The Text encoding to read the initialization file.</param>
Public Shared Function Has(Optional ByVal Encoding As System.Text.Encoding = Nothing) As Boolean
If Content Is Nothing Then [File].Get(Encoding)
Return (From line In Content Where line.Trim Like "[[]?*[]]").Any()
End Function
''' <summary>
''' Removes an existing section with all of it's keys and values.
''' </summary>
''' <param name="SectionName">Indicates the Section name to remove with all of it's key/values.</param>
''' <param name="Encoding">The Text encoding to read the initialization file.</param>
Public Shared Function Remove(Optional ByVal SectionName As String = Nothing,
Optional ByVal Encoding As System.Text.Encoding = Nothing) As Boolean
If Not [File].Exist() Then Return False
If Not SectionName Like "[[]?*[]]" Then
Throw New SectionNameInvalidFormatException
Exit Function
End If
[File].[Get](Encoding)
Select Case [Section].GetNames(Encoding).Where(Function(line) line.Trim.Equals(SectionName.Trim, CompareMode)).Any
Case True ' An existing Section name is equal to given section name.
' Get the section StartIndex and EndIndex.
[Get](SectionName)
' Remove the section range index.
Content.RemoveRange(SectionStartIndex, SectionEndIndex - SectionStartIndex)
' Save changes.
Return [File].Write(Content, Encoding)
Case Else ' Any of the existing Section names is equal to given section name.
Return False
End Select
End Function
End Class
#End Region
End Class
#End Region
Here are some usage examples:
' Set the initialization file path.
'INIFileManager.FilePath = IO.Path.Combine(Application.StartupPath, "Config.ini")
' Create the initialization file.
'INIFileManager.File.Create()
' Check that the initialization file exist.
'MsgBox(INIFileManager.File.Exist)
' Writes a new entire initialization file with the specified text content.
'INIFileManager.File.Write(New List(Of String) From {"[Section Name 1]"})
' Set an existing value or append it at the enf of the initialization file.
'INIFileManager.Key.Set("KeyName1", "Value1")
' Set an existing value on a specific section or append them at the enf of the initialization file.
'INIFileManager.Key.Set("KeyName2", "Value2", "[Section Name 2]")
' Gets the value of the specified Key name,
'MsgBox(INIFileManager.Key.Get("KeyName1"))
' Gets the value of the specified Key name on the specified Section.
'MsgBox(INIFileManager.Key.Get("KeyName2", , "[Section Name 2]"))
' Gets the value of the specified Key name and returns a default value if the key name is not found.
'MsgBox(INIFileManager.Key.Get("KeyName0", "I'm a default value"))
' Gets the value of the specified Key name, and assign it to a control property.
'CheckBox1.Checked = CType(INIFileManager.Key.Get("KeyName1"), Boolean)
' Checks whether a Key exists.
'MsgBox(INIFileManager.Key.Exist("KeyName1"))
' Checks whether a Key exists on a specific section.
'MsgBox(INIFileManager.Key.Exist("KeyName2", "[First Section]"))
' Remove a key name.
'INIFileManager.Key.Remove("KeyName1")
' Remove a key name on the specified Section.
'INIFileManager.Key.Remove("KeyName2", "[Section Name 2]")
' Add a new section.
'INIFileManager.Section.Add("[Section Name 3]")
' Get the contents of a specific section.
'MsgBox(String.Join(Environment.NewLine, INIFileManager.Section.Get("[Section Name 1]")))
' Remove an existing section.
'INIFileManager.Section.Remove("[Section Name 2]")
'' Checks that the initialization file contains at least one section.
'MsgBox(INIFileManager.Section.Has())
'' Sort the initialization file (And remove empty lines).
'INIFileManager.File.Sort(True)
'' Gets the initialization file section names.
'MsgBox(String.Join(", ", INIFileManager.Section.GetNames()))
'' Gets the initialization file content.
'MsgBox(String.Join(Environment.NewLine, INIFileManager.File.Get()))
'' Delete the initialization file from disk.
'INIFileManager.File.Delete()
I suggest using an app.config instead. Using ConfigurationManager class, you can easily read/write multiple sections with little to no code. INI is going away as means of configuration, XML will probably stay for some time, I'd say stick to that. I recently wrote an article showing simple usage:
VB.NET - Reading and writing app.config # neolisk.com
Relevant parts are included here for convenience:
Imports System.Configuration
Imports System.Reflection
Public Class AppConfig
Private _config As Configuration
Private _settings As AppSettingsSection
Public Function GetProperty(propertyName As String) As String
Return _settings.Settings.Item(propertyName).Value
End Function
Public Sub SetProperty(propertyName As String, propertyValue As String)
_settings.Settings.Item(propertyName).Value = propertyValue
End Sub
Public Sub New()
_config = ConfigurationManager.OpenExeConfiguration(
Assembly.GetEntryAssembly().Location)
_settings = _config.AppSettings
End Sub
Protected Overrides Sub Finalize()
MyBase.Finalize()
_config.Save(ConfigurationSaveMode.Modified)
End Sub
End Class
Usage:
Dim _appConfig As New AppConfig
_appConfig.SetProperty(propertyName, propertyValue)
_appConfig.GetProperty(propertyName)
You will need to extend the above class to support multiple sections.
I am looking for an automatic method to create a shortcut to a network connection in Windows 7. I do not believe this is the same as a shortcut to a file.
I would prefer it to be in vb.net, but anything (VBS, PowerShell, etc...) would be fine.
I came up with the following script, but it requires you to click yes.
Const CSIDL_CONNECTIONS = &H31
Dim objShell As Object = CreateObject("Shell.Application")
Dim objConnectionsFolder = objShell.NameSpace(CSIDL_CONNECTIONS)
For Each objConnection In objConnectionsFolder.Items
If objConnection.name = "Local Area Connection" Then
Dim colVerbs = objConnection.Verbs
For Each objVerb In colVerbs
If Replace(objVerb.name, "&", "") = "Create Shortcut" Then
objVerb.DoIt()
End If
Next
End If
Next
MsgBox("If the script ends too quickly then it doesn't finish.")
Any Suggestions would be greatly appreciated.
Powershell:
$WshShell = New-Object -comObject WScript.Shell
$Shortcut = $WshShell.CreateShortcut("C:\somepath\shortcutName.lnk"));
$Shortcut.TargetPath = "\\server\path";
$Shortcut.Save();
In VB.NET you could try to use my Shortcut Manager Helper Class.
Usage:
Dim Shortcut As New ShortcutManager.ShortcutInfo
With Shortcut
.ShortcutFile = "C:\New shortcut.lnk"
.Target = "\\server\path"
.Description = "Shortcut Description"
.Icon = "Icon.ico"
.IconIndex = 0
End With
ShortcutManager.CreateShortcut(Shortcut)
The Class is partially defined 'cause the character limit of StackOverflow (if you want the full version then go this link):
' ***********************************************************************
' Author : Elektro
' Modified : 02-16-2014
' ***********************************************************************
' <copyright file="ShortcutManager.vb" company="Elektro Studios">
' Copyright (c) Elektro Studios. All rights reserved.
' </copyright>
' ***********************************************************************
#Region " Imports "
Imports System.Runtime.InteropServices
Imports System.Text
Imports System.IO
#End Region
#Region " ShortcutManager "
''' <summary>
''' Performs Shortcut related operations.
''' </summary>
Public Class ShortcutManager
#Region " Variables "
Private Shared lnk As New ShellLink()
Private Shared lnk_data As New WIN32_FIND_DATAW()
Private Shared lnk_arguments As New StringBuilder(260)
Private Shared lnk_description As New StringBuilder(260)
Private Shared lnk_target As New StringBuilder(260)
Private Shared lnk_workingdir As New StringBuilder(260)
Private Shared lnk_iconpath As New StringBuilder(260)
Private Shared lnk_iconindex As Integer = -1
Private Shared lnk_hotkey As Short = -1
Private Shared lnk_windowstate As ShortcutWindowState = ShortcutWindowState.Normal
#End Region
#Region " P/Invoke "
<DllImport("shfolder.dll", CharSet:=CharSet.Auto)>
Private Shared Function SHGetFolderPath(
ByVal hwndOwner As IntPtr,
ByVal nFolder As Integer,
ByVal hToken As IntPtr,
ByVal dwFlags As Integer,
ByVal lpszPath As StringBuilder
) As Integer
End Function
<Flags()>
Private Enum SLGP_FLAGS
''' <summary>
''' Retrieves the standard short (8.3 format) file name.
''' </summary>
SLGP_SHORTPATH = &H1
''' <summary>
''' Retrieves the Universal Naming Convention (UNC) path name of the file.
''' </summary>
SLGP_UNCPRIORITY = &H2
''' <summary>
''' Retrieves the raw path name.
''' A raw path is something that might not exist and may include environment variables that need to be expanded.
''' </summary>
SLGP_RAWPATH = &H4
End Enum
<Flags()>
Private Enum SLR_FLAGS
''' <summary>
''' Do not display a dialog box if the link cannot be resolved. When SLR_NO_UI is set,
''' the high-order word of fFlags can be set to a time-out value that specifies the
''' maximum amount of time to be spent resolving the link. The function returns if the
''' link cannot be resolved within the time-out duration. If the high-order word is set
''' to zero, the time-out duration will be set to the default value of 3,000 milliseconds
''' (3 seconds). To specify a value, set the high word of fFlags to the desired time-out
''' duration, in milliseconds.
''' </summary>
SLR_NO_UI = &H1
''' <summary>
''' If the link object has changed, update its path and list of identifiers.
''' If SLR_UPDATE is set, you do not need to call IPersistFile::IsDirty to determine,
''' whether or not the link object has changed.
''' </summary>
SLR_UPDATE = &H4
''' <summary>
''' Do not update the link information
''' </summary>
SLR_NOUPDATE = &H8
''' <summary>
''' Do not execute the search heuristics
''' </summary>
SLR_NOSEARCH = &H10
''' <summary>
''' Do not use distributed link tracking
''' </summary>
SLR_NOTRACK = &H20
''' <summary>
''' Disable distributed link tracking.
''' By default, distributed link tracking tracks removable media,
''' across multiple devices based on the volume name.
''' It also uses the Universal Naming Convention (UNC) path to track remote file systems,
''' whose drive letter has changed.
''' Setting SLR_NOLINKINFO disables both types of tracking.
''' </summary>
SLR_NOLINKINFO = &H40
''' <summary>
''' Call the Microsoft Windows Installer
''' </summary>
SLR_INVOKE_MSI = &H80
End Enum
''' <summary>
''' Stores information about a shortcut file.
''' </summary>
Public Class ShortcutInfo
''' <summary>
''' Shortcut file full path.
''' </summary>
Public Property ShortcutFile As String
''' <summary>
''' Shortcut Comment/Description.
''' </summary>
Public Property Description As String
''' <summary>
''' Shortcut Target Arguments.
''' </summary>
Public Property Arguments As String
''' <summary>
''' Shortcut Target.
''' </summary>
Public Property Target As String
''' <summary>
''' Shortcut Working Directory.
''' </summary>
Public Property WorkingDir As String
''' <summary>
''' Shortcut Icon Location.
''' </summary>
Public Property Icon As String
''' <summary>
''' Shortcut Icon Index.
''' </summary>
Public Property IconIndex As Integer
''' <summary>
''' Shortcut Hotkey combination.
''' Is represented as Hexadecimal.
''' </summary>
Public Property Hotkey As Short
''' <summary>
''' Shortcut Hotkey modifiers.
''' </summary>
Public Property Hotkey_Modifier As HotkeyModifiers
''' <summary>
''' Shortcut Hotkey Combination.
''' </summary>
Public Property Hotkey_Key As Keys
''' <summary>
''' Shortcut Window State.
''' </summary>
Public Property WindowState As ShortcutWindowState
''' <summary>
''' Indicates if the target is a file.
''' </summary>
Public Property IsFile As Boolean
''' <summary>
''' Indicates if the target is a directory.
''' </summary>
Public Property IsDirectory As Boolean
''' <summary>
''' Shortcut target drive letter.
''' </summary>
Public Property DriveLetter As String
''' <summary>
''' Shortcut target directory name.
''' </summary>
Public Property DirectoryName As String
''' <summary>
''' Shortcut target filename.
''' (File extension is not included in name)
''' </summary>
Public Property FileName As String
''' <summary>
''' Shortcut target file extension.
''' </summary>
Public Property FileExtension As String
End Class
''' <summary>
''' Hotkey modifiers for a shortcut file.
''' </summary>
<Flags()>
Public Enum HotkeyModifiers As Short
''' <summary>
''' The SHIFT key.
''' </summary>
SHIFT = 1
''' <summary>
''' The CTRL key.
''' </summary>
CONTROL = 2
''' <summary>
''' The ALT key.
''' </summary>
ALT = 4
''' <summary>
''' None.
''' Specifies any hotkey modificator.
''' </summary>
NONE = 0
End Enum
''' <summary>
''' The Window States for a shortcut file.
''' </summary>
Public Enum ShortcutWindowState As Integer
''' <summary>
''' Shortcut Window is at normal state.
''' </summary>
Normal = 1
''' <summary>
''' Shortcut Window is Maximized.
''' </summary>
Maximized = 3
''' <summary>
''' Shortcut Window is Minimized.
''' </summary>
Minimized = 7
End Enum
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)>
Private Structure WIN32_FIND_DATAW
Public dwFileAttributes As UInteger
Public ftCreationTime As Long
Public ftLastAccessTime As Long
Public ftLastWriteTime As Long
Public nFileSizeHigh As UInteger
Public nFileSizeLow As UInteger
Public dwReserved0 As UInteger
Public dwReserved1 As UInteger
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=260)>
Public cFileName As String
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=14)>
Public cAlternateFileName As String
End Structure
''' <summary>
''' The IShellLink interface allows Shell links to be created, modified, and resolved
''' </summary>
<ComImport(),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown),
Guid("000214F9-0000-0000-C000-000000000046")>
Private Interface IShellLinkW
''' <summary>
''' Retrieves the path and file name of a Shell link object.
''' </summary>
Sub GetPath(<Out(), MarshalAs(UnmanagedType.LPWStr)>
ByVal pszFile As StringBuilder,
ByVal cchMaxPath As Integer,
ByRef pfd As WIN32_FIND_DATAW,
ByVal fFlags As SLGP_FLAGS)
''' <summary>
''' Retrieves the list of item identifiers for a Shell link object.
''' </summary>
Sub GetIDList(ByRef ppidl As IntPtr)
''' <summary>
''' Sets the pointer to an item identifier list (PIDL) for a Shell link object.
''' </summary>
Sub SetIDList(ByVal pidl As IntPtr)
''' <summary>
''' Retrieves the description string for a Shell link object.
''' </summary>
Sub GetDescription(<Out(), MarshalAs(UnmanagedType.LPWStr)>
ByVal pszName As StringBuilder,
ByVal cchMaxName As Integer)
''' <summary>
''' Sets the description for a Shell link object.
''' The description can be any application-defined string.
''' </summary>
Sub SetDescription(<MarshalAs(UnmanagedType.LPWStr)>
ByVal pszName As String)
''' <summary>
''' Retrieves the name of the working directory for a Shell link object.
''' </summary>
Sub GetWorkingDirectory(<Out(), MarshalAs(UnmanagedType.LPWStr)>
ByVal pszDir As StringBuilder,
ByVal cchMaxPath As Integer)
''' <summary>
''' Sets the name of the working directory for a Shell link object.
''' </summary>
Sub SetWorkingDirectory(<MarshalAs(UnmanagedType.LPWStr)>
ByVal pszDir As String)
''' <summary>
''' Retrieves the command-line arguments associated with a Shell link object.
''' </summary>
Sub GetArguments(<Out(), MarshalAs(UnmanagedType.LPWStr)>
ByVal pszArgs As StringBuilder,
ByVal cchMaxPath As Integer)
''' <summary>
''' Sets the command-line arguments for a Shell link object.
''' </summary>
Sub SetArguments(<MarshalAs(UnmanagedType.LPWStr)>
ByVal pszArgs As String)
''' <summary>
''' Retrieves the hot key for a Shell link object.
''' </summary>
Sub GetHotkey(ByRef pwHotkey As Short)
''' <summary>
''' Sets a hot key for a Shell link object.
''' </summary>
Sub SetHotkey(ByVal wHotkey As Short)
''' <summary>
''' Retrieves the show command for a Shell link object.
''' </summary>
Sub GetShowCmd(ByRef piShowCmd As Integer)
''' <summary>
''' Sets the show command for a Shell link object.
''' The show command sets the initial show state of the window.
''' </summary>
Sub SetShowCmd(ByVal iShowCmd As ShortcutWindowState)
''' <summary>
''' Retrieves the location (path and index) of the icon for a Shell link object.
''' </summary>
Sub GetIconLocation(<Out(), MarshalAs(UnmanagedType.LPWStr)>
ByVal pszIconPath As StringBuilder,
ByVal cchIconPath As Integer,
ByRef piIcon As Integer)
''' <summary>
''' Sets the location (path and index) of the icon for a Shell link object.
''' </summary>
Sub SetIconLocation(<MarshalAs(UnmanagedType.LPWStr)>
ByVal pszIconPath As String,
ByVal iIcon As Integer)
''' <summary>
''' Sets the relative path to the Shell link object.
''' </summary>
Sub SetRelativePath(<MarshalAs(UnmanagedType.LPWStr)>
ByVal pszPathRel As String,
ByVal dwReserved As Integer)
''' <summary>
''' Attempts to find the target of a Shell link,
''' even if it has been moved or renamed.
''' </summary>
Sub Resolve(ByVal hwnd As IntPtr,
ByVal fFlags As SLR_FLAGS)
''' <summary>
''' Sets the path and file name of a Shell link object
''' </summary>
Sub SetPath(ByVal pszFile As String)
End Interface
<ComImport(), Guid("0000010c-0000-0000-c000-000000000046"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
Private Interface IPersist
<PreserveSig()>
Sub GetClassID(ByRef pClassID As Guid)
End Interface
<ComImport(), Guid("0000010b-0000-0000-C000-000000000046"),
InterfaceType(ComInterfaceType.InterfaceIsIUnknown)>
Private Interface IPersistFile
Inherits IPersist
Shadows Sub GetClassID(ByRef pClassID As Guid)
<PreserveSig()>
Function IsDirty() As Integer
<PreserveSig()>
Sub Load(<[In](), MarshalAs(UnmanagedType.LPWStr)>
pszFileName As String,
dwMode As UInteger)
<PreserveSig()>
Sub Save(<[In](), MarshalAs(UnmanagedType.LPWStr)>
pszFileName As String,
<[In](), MarshalAs(UnmanagedType.Bool)>
fRemember As Boolean)
<PreserveSig()>
Sub SaveCompleted(<[In](), MarshalAs(UnmanagedType.LPWStr)>
pszFileName As String)
<PreserveSig()>
Sub GetCurFile(<[In](), MarshalAs(UnmanagedType.LPWStr)>
ppszFileName As String)
End Interface
' "CLSID_ShellLink" from "ShlGuid.h"
<ComImport(),
Guid("00021401-0000-0000-C000-000000000046")>
Private Class ShellLink
End Class
#End Region
#Region " Public Methods "
''' <summary>
''' Creates a shortcut file.
''' </summary>
''' <param name="FilePath">
''' The filepath to create the shortcut.
''' </param>
''' <param name="Target">
''' The target file or directory.
''' </param>
''' <param name="WorkingDirectory">
''' The working directory os the shortcut.
''' </param>
''' <param name="Description">
''' The shortcut description.
''' </param>
''' <param name="Arguments">
''' The target file arguments.
''' This value only should be set when target is an executable file.
''' </param>
''' <param name="Icon">
''' The icon location of the shortcut.
''' </param>
''' <param name="IconIndex">
''' The icon index of the icon file.
''' </param>
''' <param name="HotKey_Modifier">
''' The hotkey modifier(s) which should be used for the hotkey combination.
''' <paramref name="HotkeyModifiers"/> can be one or more modifiers.
''' </param>
''' <param name="HotKey_Key">
''' The key used in combination with the <paramref name="HotkeyModifiers"/> for hotkey combination.
''' </param>
''' <param name="WindowState">
''' The Window state for the target.
''' </param>
Public Shared Sub CreateShortcut(ByVal FilePath As String,
ByVal Target As String,
Optional ByVal WorkingDirectory As String = Nothing,
Optional ByVal Description As String = Nothing,
Optional ByVal Arguments As String = Nothing,
Optional ByVal Icon As String = Nothing,
Optional ByVal IconIndex As Integer = Nothing,
Optional ByVal HotKey_Modifier As HotkeyModifiers = Nothing,
Optional ByVal HotKey_Key As Keys = Nothing,
Optional ByVal WindowState As ShortcutWindowState = ShortcutWindowState.Normal)
' Load Shortcut
LoadShortcut(FilePath)
' Clean objects
Clean()
' Set Shortcut Info
DirectCast(lnk, IShellLinkW).SetPath(Target)
DirectCast(lnk, IShellLinkW).SetWorkingDirectory(If(WorkingDirectory IsNot Nothing,
WorkingDirectory,
Path.GetDirectoryName(Target)))
DirectCast(lnk, IShellLinkW).SetDescription(Description)
DirectCast(lnk, IShellLinkW).SetArguments(Arguments)
DirectCast(lnk, IShellLinkW).SetIconLocation(Icon, IconIndex)
DirectCast(lnk, IShellLinkW).SetHotkey(If(HotKey_Modifier + HotKey_Key <> 0,
Convert.ToInt16(CInt(HotKey_Modifier & Hex(HotKey_Key)), 16),
Nothing))
DirectCast(lnk, IShellLinkW).SetShowCmd(WindowState)
DirectCast(lnk, IPersistFile).Save(FilePath, True)
DirectCast(lnk, IPersistFile).SaveCompleted(FilePath)
End Sub
''' <summary>
''' Creates a shortcut file.
''' </summary>
''' <param name="Shortcut">Indicates a ShortcutInfo object.</param>
Public Shared Sub CreateShortcut(ByVal Shortcut As ShortcutInfo)
CreateShortcut(Shortcut.ShortcutFile,
Shortcut.Target,
Shortcut.WorkingDir,
Shortcut.Description,
Shortcut.Arguments,
Shortcut.Icon,
Shortcut.IconIndex,
Shortcut.Hotkey_Modifier,
Shortcut.Hotkey_Key,
Shortcut.WindowState)
End Sub
#End Region
#Region " Private Methods "
''' <summary>
''' Loads the shortcut object to retrieve information.
''' </summary>
''' <param name="ShortcutFile">
''' The shortcut file to retrieve the info.
''' </param>
Private Shared Sub LoadShortcut(ByVal ShortcutFile As String)
DirectCast(lnk, IPersistFile).Load(ShortcutFile, 0)
End Sub
''' <summary>
''' Clean the shortcut info objects.
''' </summary>
Private Shared Sub Clean()
lnk_description.Clear()
lnk_arguments.Clear()
lnk_target.Clear()
lnk_workingdir.Clear()
lnk_iconpath.Clear()
lnk_hotkey = -1
lnk_iconindex = -1
End Sub
''' <summary>
''' Gets the low order byte of a number.
''' </summary>
Private Shared Function GetLoByte(ByVal Intg As Integer) As Integer
Return Intg And &HFF&
End Function
''' <summary>
''' Gets the high order byte of a number.
''' </summary>
Private Shared Function GetHiByte(ByVal Intg As Integer) As Integer
Return (Intg And &HFF00&) / 256
End Function
#End Region
End Class
#End Region
So I'm working on a simple VB.net game for school, in which you pop bubbles. We need to have a sound play when you pop a bubble, which is very simple with the audio play function;
Private Sub bubblePop(sender As Object, e As EventArgs) Handles bubble.Click
My.Computer.Audio.Play(My.Resources.pop, _
AudioPlayMode.Background)
End Sub
However we also have a little backing track for the game that we want to loop in the background infinitely. We tried this with a similar instance of that function;
Private Sub GameScreen_Load(sender As Object, e As EventArgs) Handles MyBase.Load
My.Computer.Audio.Play(My.Resources.musicLoop, _
AudioPlayMode.BackgroundLoop)
End Sub
The function shown above only allows one audio file to be played at once, meaning when a bubble is popped the music disappears for good.
I've tried using two seperate windows media player things, but that isn't working either;
Public pop As String = "pop.wav"
Public minesound As String = "mine.wav"
Public Sub soundEffects(sound)
If sound = pop Then
GameScreen.AxWindowsMediaPlayer2.URL = pop
ElseIf sound = minesound Then
GameScreen.AxWindowsMediaPlayer2.URL = minesound
End If
End Sub
Any help or advice is very appreciated! Thank you!
Basically you need to run an asynchronous operation to play more than one file at once.
I've started writting a solution using My.Computer method but even using a Task/Thread it seems that (strangely) is not sufficient to play a secondary file without stopping the playback of the first file ran so maybe other factor (unknown for me) could be involved, then I've solved it using MCI.
The usage can be this:
Dim TaskCancellationTokenSource As New CancellationTokenSource
Dim TaskToken As CancellationToken = TaskCancellationTokenSource.Token
Private Sub BubbleLoop(ByVal CancellationToken As Threading.CancellationToken)
Dim AudioFileLoop = New MCIPlayer(Me, "C:\BubbleLoop.wav")
Do Until CancellationToken.IsCancellationRequested
AudioFileLoop.Play(AudioPlayMode.WaitToComplete)
Loop
AudioFileLoop.Close()
End Sub
Private Sub Test()
' This plays a file asynchronously into an infinite loop.
Task.Factory.StartNew(Sub() BubbleLoop(TaskToken), TaskToken)
' Wait 2 seconds (just to demonstrate this example)
Threading.Thread.Sleep(2 * 1000)
' Play any other file while the loop is still playing.
Dim AudioFile = New MCIPlayer(Me, "C:\SingleBubble.mp3")
AudioFile.Play(AudioPlayMode.Background)
' Cancel the Bubble Loop.
TaskCancellationTokenSource.Cancel()
End Sub
And you need to add this basic MCI class that I've did (It's not full tsted):
' [ MCI Player ]
'
' // By Elektro H#cker
#Region " Usage Examples "
'Dim AudioFile As New MCIPlayer(Me, "C:\Audio.wav")
'AudioFile.Play(AudioPlayMode.BackgroundLoop)
'Dim sb As New System.Text.StringBuilder
'sb.AppendLine("Filename: " & AudioFile.Filename)
'sb.AppendLine("State...: " & AudioFile.State.ToString)
'sb.AppendLine("Mode....: " & AudioFile.PlaybackMode.ToString)
'sb.AppendLine("Channels: " & CStr(AudioFile.Channels))
'sb.AppendLine("Duration: " & TimeSpan.FromMilliseconds(AudioFile.Duration).ToString("hh\:mm\:ss"))
'MessageBox.Show(sb.ToString, "MCI Player", MessageBoxButtons.OK, MessageBoxIcon.Information)
'AudioFile.Stop()
#End Region
#Region " MCI Player "
''' <summary>
''' Play Wave, MP3 or MIDI files
''' </summary>
Public Class MCIPlayer
Inherits NativeWindow
Implements IDisposable
#Region " API "
''' <summary>
''' Sends a command string to an MCI device.
''' The device that the command is sent to is specified in the command string.
''' </summary>
''' <param name="command">
''' Pointer to a null-terminated string that specifies an MCI command string.
''' For a list, see Multimedia Command Strings.
''' </param>
''' <param name="buffer">
''' Buffer that receives return information.
''' If no return information is needed, this parameter can be NULL.
''' </param>
''' <param name="bufferSize">
''' Size, in characters, of the return buffer specified.
''' </param>
''' <param name="hwndCallback">
''' Handle to a callback window if the "notify" flag was specified in the command string.
''' </param>
<System.Runtime.InteropServices.
DllImport("winmm.dll", SetLastError:=True)>
Private Shared Function mciSendString(
ByVal command As String,
ByVal buffer As System.Text.StringBuilder,
ByVal bufferSize As Integer,
ByVal hwndCallback As IntPtr
) As Integer
End Function
#End Region
#Region " Variables "
''' <summary>
''' The form to manage Windows Messages.
''' </summary>
Private WithEvents form As Form = Nothing
''' <summary>
''' Indicates the audio play command of mciSendString.
''' </summary>
Private PlayCommand As String = String.Empty
''' <summary>
''' Buffer that receives return information.
''' </summary>
Private ReturnInfo As New System.Text.StringBuilder() With {.Capacity = 255}
''' <summary>
''' The current filename of the file that is to be played.
''' </summary>
Private _filename As String = String.Empty
''' <summary>
''' Indicates the current playback mode.
''' </summary>
Private _PlaybackMode As AudioPlayMode
''' <summary>
''' Flag to cancel the BackgroundLoop PlaybackMode.
''' </summary>
Private CancelLoop As Boolean = False
#End Region
#Region " Properties "
''' <summary>
''' The current filename of the file that is to be played.
''' </summary>
Public Property Filename() As String
Get
Return _filename
End Get
Set(ByVal value As String)
If Not IO.File.Exists(value) Then
Throw New IO.FileNotFoundException
Exit Property
End If
_filename = value
End Set
End Property
''' <summary>
''' Gets che current Playback State.
''' </summary>
Public ReadOnly Property State As PlaybackState
Get
mciSendString("status file mode", ReturnInfo, ReturnInfo.Capacity, IntPtr.Zero)
Return [Enum].Parse(GetType(PlaybackState), ReturnInfo.ToString, True)
End Get
End Property
''' <summary>
''' Gets or sets the playback mode of the current file.
''' </summary>
Public Property PlaybackMode As AudioPlayMode
Get
Return _PlaybackMode
End Get
Set(value As AudioPlayMode)
_PlaybackMode = value
End Set
End Property
''' <summary>
''' Gets the channels of the file.
''' </summary>
ReadOnly Property Channels() As Integer
Get
mciSendString("status file channels", ReturnInfo, ReturnInfo.Capacity, IntPtr.Zero)
Return If(IsNumeric(ReturnInfo.ToString),
CInt(ReturnInfo.ToString),
-1)
End Get
End Property
''' <summary>
''' Gets the file duration in Milleseconds.
''' </summary>
ReadOnly Property Duration() As Integer
Get
mciSendString("set file time format milliseconds", Nothing, 0, IntPtr.Zero)
mciSendString("status file length", ReturnInfo, ReturnInfo.Capacity, IntPtr.Zero)
Return If(String.IsNullOrEmpty(ReturnInfo.ToString), 0, CInt(ReturnInfo.ToString))
End Get
End Property
#End Region
#Region " Enumerations "
''' <summary>
''' Audio File playback state.
''' </summary>
Public Enum PlaybackState As Short
''' <summary>
''' File is playing.
''' </summary>
Playing = 0
''' <summary>
''' File is paused.
''' </summary>
Paused = 1
''' <summary>
''' File is stopped.
''' </summary>
Stopped = 2
End Enum
''' <summary>
''' Windows Message Identifiers.
''' </summary>
Public Enum KnownMessages As Integer
''' <summary>
''' Notifies an application that an MCI device has completed an operation.
''' MCI devices send this message only when the MCI_NOTIFY flag is used.
''' </summary>
MM_MCINOTIFY = 953
End Enum
#End Region
#Region " Constructor "
''' <summary>
''' Play Wave, MP3 or MIDI files.
''' </summary>
''' <param name="AudioFile">Indicates the filename of the media to play.</param>
''' <remarks></remarks>
Public Sub New(ByVal form As Form, ByVal AudioFile As String)
Me.Filename = AudioFile
' Set the Formulary.
Me.form = form
' Assign the form handle.
SetFormHandle()
End Sub
#End Region
#Region " Public Methods "
''' <summary>
''' Plays the file that is specified as the filename.
''' </summary>
''' <remarks></remarks>
Public Sub Play(ByVal PlayMode As AudioPlayMode)
DisposedCheck()
Select Case PlayMode
Case AudioPlayMode.Background
PlayCommand = "play file from 0"
Me.PlaybackMode = AudioPlayMode.Background
Case AudioPlayMode.BackgroundLoop
PlayCommand = "play file from 0 notify"
Me.PlaybackMode = AudioPlayMode.BackgroundLoop
Case AudioPlayMode.WaitToComplete
PlayCommand = "play file from 0 wait"
Me.PlaybackMode = AudioPlayMode.WaitToComplete
End Select
' Open command
Select Case Me.Filename.Split(".").LastOrDefault
Case "mp3"
mciSendString(String.Format("open ""{0}"" type mpegvideo alias file", Me.Filename),
Nothing,
0,
IntPtr.Zero)
Case "wav"
mciSendString(String.Format("open ""{0}"" type waveaudio alias file", Me.Filename),
Nothing,
0,
IntPtr.Zero)
Case "mid", "midi"
mciSendString("stop midi", Nothing, 0, 0)
mciSendString("close midi", Nothing, 0, 0)
mciSendString(String.Format("open sequencer! ""{0}"" alias file", Me.Filename),
Nothing,
0, IntPtr.Zero)
Case Else
Throw New Exception("File type not supported.")
[Close]()
End Select
' Play command
mciSendString(PlayCommand, Nothing, 0, If(PlaybackMode = AudioPlayMode.BackgroundLoop,
Me.Handle,
IntPtr.Zero))
End Sub
''' <summary>
''' Pause the current playback.
''' </summary>
''' <remarks></remarks>
Public Sub Pause()
DisposedCheck()
CancelLoop = True
mciSendString("pause file", Nothing, 0, IntPtr.Zero)
End Sub
''' <summary>
''' Resume the current playback if it is currently paused.
''' </summary>
Public Sub [Resume]()
DisposedCheck()
If Me.State = PlaybackState.Paused Then
CancelLoop = False
mciSendString("resume file", Nothing, 0, IntPtr.Zero)
End If
End Sub
''' <summary>
''' Stop the current playback.
''' </summary>
Public Sub [Stop]()
DisposedCheck()
CancelLoop = True
mciSendString("stop file", Nothing, 0, IntPtr.Zero)
End Sub
''' <summary>
''' Close the current file.
''' </summary>
Public Overloads Sub [Close]()
DisposedCheck()
CancelLoop = True
mciSendString("close file", Nothing, 0, IntPtr.Zero)
End Sub
#End Region
#Region " Event Handlers "
''' <summary>
''' Assign the handle of the target form to this NativeWindow,
''' necessary to override WndProc.
''' </summary>
Private Sub SetFormHandle() _
Handles form.HandleCreated, form.Load, form.Shown
Try
If Not Me.Handle.Equals(Me.form.Handle) Then
Me.AssignHandle(Me.form.Handle)
End If
Catch ' ex As InvalidOperationException
End Try
End Sub
''' <summary>
''' Releases the Handle.
''' </summary>
Private Sub OnHandleDestroyed() _
Handles form.HandleDestroyed
Me.ReleaseHandle()
End Sub
#End Region
#Region " Windows Messages "
''' <summary>
''' Processes Windows messages for this Window.
''' </summary>
''' <param name="m">
''' Contains the Windows Message parameters.
''' </param>
Protected Overrides Sub WndProc(ByRef m As Message)
MyBase.WndProc(m)
If m.Msg = KnownMessages.MM_MCINOTIFY Then
If Not CancelLoop Then
Play(AudioPlayMode.BackgroundLoop)
Else
CancelLoop = False
End If
End If
End Sub
#End Region
#Region " IDisposable "
''' <summary>
''' To detect redundant calls when disposing.
''' </summary>
Private IsDisposed As Boolean = False
''' <summary>
''' Prevents calls to methods after disposing.
''' </summary>
Private Sub DisposedCheck()
If Me.IsDisposed Then
Throw New ObjectDisposedException(Me.GetType().FullName)
End If
End Sub
''' <summary>
''' Disposes the objects generated by this instance.
''' </summary>
Public Sub Dispose() Implements IDisposable.Dispose
Dispose(True)
GC.SuppressFinalize(Me)
End Sub
' IDisposable
Protected Overridable Sub Dispose(IsDisposing As Boolean)
If Not Me.IsDisposed Then
If IsDisposing Then
[Close]()
Me.form = Nothing
Me.ReleaseHandle()
Me.DestroyHandle()
End If
End If
Me.IsDisposed = True
End Sub
#End Region
End Class
#End Region
I am using VB.net VS2012 and would like some help playing an Audio file.
Here is my code:
''' <summary>
''' This class is a wrapper for the Windows API calls to play wave, midi or mp3 files.
''' </summary>
''' <remarks>
''' </remarks>
Public Class AudioFile
'***********************************************************************************************************
' Class: PlayFile
' Written By: Blake Pell (bpell#indiana.edu)
' Initial Date: 03/31/2007
' Last Updated: 02/04/2009
'***********************************************************************************************************
' Windows API Declarations
Private Declare Function mciSendString Lib "winmm.dll" Alias "mciSendStringA" (ByVal lpstrCommand As String, ByVal lpstrReturnString As String, ByVal uReturnLength As Int32, ByVal hwndCallback As Int32) As Int32
''' <summary>
''' Constructor: Location is the filename of the media to play. Wave files and Mp3 files are the supported formats.
''' </summary>
''' <param name="Location"></param>
''' <remarks></remarks>
Public Sub New(ByVal location As String)
Me.Filename = location
End Sub
''' <summary>
''' Plays the file that is specified as the filename.
''' </summary>
''' <remarks></remarks>
Public Sub Play()
If _filename = "" Or Filename.Length <= 4 Then Exit Sub
Select Case Right(Filename, 3).ToLower
Case "mp3"
mciSendString("open """ & _filename & """ type mpegvideo alias audiofile", Nothing, 0, IntPtr.Zero)
Dim playCommand As String = "play audiofile from 0"
If _wait = True Then playCommand += " wait"
mciSendString(playCommand, Nothing, 0, IntPtr.Zero)
Case "wav"
mciSendString("open """ & _filename & """ type waveaudio alias audiofile", Nothing, 0, IntPtr.Zero)
mciSendString("play audiofile from 0", Nothing, 0, IntPtr.Zero)
Case "mid", "idi"
mciSendString("stop midi", "", 0, 0)
mciSendString("close midi", "", 0, 0)
mciSendString("open sequencer!" & _filename & " alias midi", "", 0, 0)
mciSendString("play midi", "", 0, 0)
Case Else
Throw New Exception("File type not supported.")
Call Close()
End Select
IsPaused = False
End Sub
''' <summary>
''' Pause the current play back.
''' </summary>
''' <remarks></remarks>
Public Sub Pause()
mciSendString("pause audiofile", Nothing, 0, IntPtr.Zero)
IsPaused = True
End Sub
''' <summary>
''' Resume the current play back if it is currently paused.
''' </summary>
''' <remarks></remarks>
Public Sub [Resume]()
mciSendString("resume audiofile", Nothing, 0, IntPtr.Zero)
IsPaused = False
End Sub
''' <summary>
''' Stop the current file if it's playing.
''' </summary>
''' <remarks></remarks>
Public Sub [Stop]()
mciSendString("stop audiofile", Nothing, 0, IntPtr.Zero)
End Sub
''' <summary>
''' Close the file.
''' </summary>
''' <remarks></remarks>
Public Sub Close()
mciSendString("close audiofile", Nothing, 0, IntPtr.Zero)
End Sub
Private _wait As Boolean = False
''' <summary>
''' Halt the program until the .wav file is done playing. Be careful, this will lock the entire program up until the
''' file is done playing. It behaves as if the Windows Sleep API is called while the file is playing (and maybe it is, I don't
''' actually know, I'm just theorizing). :P
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property Wait() As Boolean
Get
Return _wait
End Get
Set(ByVal value As Boolean)
_wait = value
End Set
End Property
''' <summary>
''' Sets the audio file's time format via the mciSendString API.
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
ReadOnly Property Milleseconds() As Integer
Get
Dim buf As String = Space(255)
mciSendString("set audiofile time format milliseconds", Nothing, 0, IntPtr.Zero)
mciSendString("status audiofile length", buf, 255, IntPtr.Zero)
buf = Replace(buf, Chr(0), "") ' Get rid of the nulls, they muck things up
If buf = "" Then
Return 0
Else
Return CInt(buf)
End If
End Get
End Property
''' <summary>
''' Gets the status of the current playback file via the mciSendString API.
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
ReadOnly Property Status() As String
Get
Dim buf As String = Space(255)
mciSendString("status audiofile mode", buf, 255, IntPtr.Zero)
buf = Replace(buf, Chr(0), "") ' Get rid of the nulls, they muck things up
Return buf
End Get
End Property
''' <summary>
''' Gets the file size of the current audio file.
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
ReadOnly Property FileSize() As Integer
Get
Try
Return My.Computer.FileSystem.GetFileInfo(_filename).Length
Catch ex As Exception
Return 0
End Try
End Get
End Property
''' <summary>
''' Gets the channels of the file via the mciSendString API.
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
ReadOnly Property Channels() As Integer
Get
Dim buf As String = Space(255)
mciSendString("status audiofile channels", buf, 255, IntPtr.Zero)
If IsNumeric(buf) = True Then
Return CInt(buf)
Else
Return -1
End If
End Get
End Property
''' <summary>
''' Used for debugging purposes.
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
ReadOnly Property Debug() As String
Get
Dim buf As String = Space(255)
mciSendString("status audiofile channels", buf, 255, IntPtr.Zero)
Return Str(buf)
End Get
End Property
Private _isPaused As Boolean = False
''' <summary>
''' Whether or not the current playback is paused.
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property IsPaused() As Boolean
Get
Return _isPaused
End Get
Set(ByVal value As Boolean)
_isPaused = value
End Set
End Property
Private _filename As String
''' <summary>
''' The current filename of the file that is to be played back.
''' </summary>
''' <value></value>
''' <returns></returns>
''' <remarks></remarks>
Public Property Filename() As String
Get
Return _filename
End Get
Set(ByVal value As String)
If My.Computer.FileSystem.FileExists(value) = False Then
Throw New System.IO.FileNotFoundException
Exit Property
End If
_filename = value
End Set
End Property
End Class
This code works well. Can I please have some help to create an Event that will be called when the Audio file has finished playing. When an Audio file has finished, the 'Status' is 'Stopped'. How can I check to see when this happens and create an Event for it?
There doesn't seem to a way to register a callback for when the playback status changes, so you'll have to use an observer (i.e. a timer).
Private WithEvents StatusMonitor As New Timers.Timer(100)
Private Property LastStatus As String
Private Sub StatusMonitor_Elapsed(sender As Object, e As Timers.ElapsedEventArgs) Handles StatusMonitor.Elapsed
If Not String.Equals(Me.Status, Me.LastStatus) Then
Me.LastStatus = Me.Status
RaiseEvent PlaybackStatusChanged(Me, New PlaybackStatusChangedEventArgs(Me.Status))
End If
End Sub
Public Event PlaybackStatusChanged(sender As Object, e As PlaybackStatusChangedEventArgs)
Public Class PlaybackStatusChangedEventArgs
Inherits EventArgs
Private _status As String
Public Sub New(status As String)
_status = status
End Sub
Public ReadOnly Property Status As String
Get
Return _status
End Get
End Property
End Class
What this does is it stores the status in a private property and compares it to the current status every 100ms. If the status has changed, it fires the PlaybackStatusChanged event, along with arguments containing the new status. You can then listen for this event, and check e.Status in the event callback as if you were directly getting it from AudioFile.Status.
EDIT
After doing a couple of test runs, I've found that the status property behaves inconsistently. It seems to return a lot of whitespace as well, for reasons that I can't seem to figure out. Anyway, as a result, the status passed to the status event is wrong.
I'm not sure how to do that. But what you could do is this. On your main form, Dim a string like lol as string
Now for a button, set this code:
lol = "Audio file path goes here :3"
Dim audio As New AudioFile(lol)
Timer1.Start()
audio.Play()
Add a timer, and set its interval to 10.
For the timer code add this:
Dim audio As New AudioFile(lol)
If audio.Status.Contains("stopped") Then
audio.Play()
End If
That way, when the song is done playing, the timer will automatically start playing it again. And its set for the audio file that's on that variable, so just have the button set the path on that variable and boom. Your set.
Hope that helped...
I have inherited a class in vb.net and when I create the object, I am only seeing one of the inherited public properties in intellisense. Any solution to this problem?
print("Public Class CompanyMailMessage
Inherits MailMessage
Private AdobeDisclaimer As String = "You will need Adobe Acrobat to read this file. If it is not installed on your computer go to http://www.adobe.com/support/downloads/main.html to download. Thank You"
Private _Body As String
Private _IncludeAdobeDisclaimer As Boolean = False
''' <summary>
''' Gets or sets the body of the message
''' </summary>
''' <returns>A System.String that contains the body content.</returns>
Public Property Body() As String
Get
If _IncludeAdobeDisclaimer Then
_Body = _Body + AdobeDisclaimer
End If
Return _Body
End Get
Set(ByVal value As String)
_Body = value
End Set
End Property
''' <summary>
''' Gets or sets a value that determines if a message that states that Adobe Acrobat must be used to open the attached files is included in the body of the message
''' </summary>
''' <value></value>
''' <returns>True if ;otherwise, false</returns>
''' <remarks></remarks>
Public Property IncludeAdobeDisclaimer() As Boolean
Get
Return _IncludeAdobeDisclaimer
End Get
Set(ByVal value As Boolean)
_IncludeAdobeDisclaimer = value
End Set
End Property
''' <summary>
''' Initializes an instance of the CompanyMailMessageclass
''' </summary>
''' <remarks></remarks>
Public Sub New()
End Sub
''' <summary>
''' Initializes an instance of the CompanyMailMessageclass with plain text in the body
''' </summary>
''' <param name="from">The email address of the sender</param>
''' <param name="fromName">The name of the sender</param>
''' <param name="to"></param>
''' <param name="subject"></param>
''' <param name="body"></param>
''' <remarks></remarks>
Public Sub New(from as String,fromName As String,[to] as String,subject As String,body As String)
MyBase.FromAddress = New EmailAddress(from,fromName)
MyBase.ToAddresses.Add([to])
MyBase.Subject = subject
_Body = body
MyBase.Items.Add(New MessageContent(MimeType.MessageRfc822,body))
End Sub");
I would suggest opening Reflector and opening the 3rd party dll. I'm guessing the properties will be internal (friend in vb.net, I think) and that's the reason.