I'm trying to create a text file and write data to it, simple right.
Well it's not working and I've looked everywhere for it but can't find an answer.
When it gets to the CreateTextFile() method it throws a path not found error. But I've made sure the path is valid and exists.
'Create a text file
Private Sub OpenFile()
Dim filePath As String
Dim fileName As String
Dim fullPath As String
Const ForAppending = 8, TristateFalse = 0
Dim curDate As Date
Dim strDate As String
curDate = Date
strDate = CStr(curDate)
fileName = "DCSSInputLitigation_" & "(" & strDate & ")" & ".txt"
filePath = "C:\TempFolder\"
Set fs = CreateObject("Scripting.FileSystemObject")
fullPath = fs.BuildPath(filePath, fileName)
Set fWriter = fs.CreateTextFile(fullPath)
End Sub
When I hard code the path in the method it works but not when I use variables. Any Ideas?
Set fWriter = fs.CreateTextFile("C:\TempFolder\test.txt")
When you get the date as follows:
strDate = CStr(curDate)
you are adding / into the file name and the string value for fullPath which you create is:
C:\TempFolder\DCSSInputLitigation_(6/12/2014).txt
File names cannot have / in them on Windows so you are running into problems here.
You can either format the date or replace the / like:
strDate = replace(CStr(curDate),"/","-")
strDate = Format(curDate,"dd-mm-yyyy")
Either will work.
Related
The below code shows oldest file name in a file directory, but I am interested in knowing the oldest file date, but not the oldest file name.
Sub oldestdate()
Range("G10").Value = GetOldestFile("xxxxx\yyyy\gggggg\uuuuuu")
End Sub
Public Function GetOldestFile(ByVal FileFolder As String, _
Optional ByVal FileMask As String = "*.*", _
Optional ByVal FullName As Boolean = True) As String
Dim FoundFile As String
Dim FileDT As Date
Dim OldestFile As String
Dim OldestDT As Date
Dim FS As Object
'// Get rid of any terminating '\' just to get to a known state
If Right(Trim(FileFolder), 1) = "\" Then
FileFolder = Left(FileFolder, Len(Trim(FileFolder)) - 1)
End If
'// Get First file found in described folder
FoundFile = Dir$(FileFolder & "\" & FileMask)
'// Default return date
OldestDT = Now
Set FS = CreateObject("Scripting.FileSystemObject")
'// Loop through the rest of the files in that folder
Do Until FoundFile = ""
FileDT = FS.GetFile(FileFolder & "\" & FoundFile).DateCreated
'// Compare Current File datetime with oldest found
If FileDT < OldestDT Then
OldestFile = FoundFile
OldestDT = FileDT
End If
'// Get next file
FoundFile = Dir$
Loop
Set FS = Nothing
GetOldestFile = Format(OldestDT, "mm/dd/yyyy")
End Function
Please check the code and let me know if you have any questions or comments.
I have got this
FileName = "Events_Data.csv"
I want to add date to this, so output required is
FileName = "Events_Data_20140521.csv"
I have got data in separate variables, just don't know how to add this before .csv in the file name.
Can anyone please help.
Regards
Chech below code
VB.Net
Dim FileName As String = "Events_Data.csv"
FileName = FileName.Replace(".csv", "_" & System.DateTime.Now.ToString("yyyyMMdd") & ".csv")
C#.Net
string FileName = "Events_Data.csv";
string ptest =System.DateTime.Now.ToString("yyyyMMdd");
FileName = FileName.Replace(".csv", "_" + ptest + ".csv");
Dim FileName As String = "Your File Name"
FileName += DateTime.Now.ToString("ddmmyyyyHHmm") + _
System.IO.Path.GetExtension(FileUpload1.FileName)
FileUpload1.SaveAs(Server.MapPath("Upload/" + FileName))
FileName = "Upload/" + FileName
You concatenate the various parts using &:
FileName = "Events_Data_" & yourDateVariable & ".csv"
Try this
if varDate is Type Date
FileName = FileName.Replace(".csv", String.Format("_{0}.csv", varDate.ToString("yyyyMMdd")))
or
is just a String
FileName = FileName.Replace(".csv", String.Format("_{0}.csv", varDate))
i found this expression,
^[<conf-start a-z0-9- =""/><month></month>]+
which matches the source string
<conf-start iso-8601-date="2011-03-04"><day>04</day><month>March</month><year>2011</year></conf-start>
but i am unable to replace the month from March to 03 for eg March should replace with 03
i tried the following code,
Dim mydir As String = TextBox1.Text
Dim filePath As String = TextBox1.Text
Dim directory1 As String = Path.GetDirectoryName(filePath)
Dim split As String() = filePath.Split("\")
Dim parentFolder As String = split(split.Length - 2)
Dim outputLines As New List(Of String)()
Dim stringToMatch As String = "^[<conf-start a-z0-9- =""/><month>March</month>]+"
Dim replacementString As String = "^[<conf-start a-z0-9- =""/><month>03</month>]+"
For Each line As String In System.IO.File.ReadAllLines(TextBox1.Text & "\" & parentFolder & ".xml")
Dim matchFound As Boolean
matchFound = line.Contains(stringToMatch)
If matchFound Then
' Replace line with string
outputLines.Add(replacementString)
Else
outputLines.Add(line)
End If
Next
System.IO.File.WriteAllLines(TextBox1.Text & "\" & parentFolder & ".xml", outputLines.ToArray(), Encoding.UTF8)
but i am unable to find changes in my xml file.
so anyone please help me with this.
still stuck with this problem.
You can use LINQ to XML and XML literals instead.
Example:
' Load the file '
Dim yourXml = XDocument.Load("your_path_to_the_file.xml").Root
' Change each monthname to the number of the month
For Each elem in yourXml ...<conf-start>.<month>
elem.value = DateTime.ParseExact(elem.value, "MMMM", System.Globalization.CultureInfo.InvariantCulture).Month
Next
' save file
yourXml.Save("your_path_to_the_file.xml")
I currently have these directories:
C:\testfolder\100
C:\testfolder\101
C:\testfolder\102
and I have these files in the same directory:
C:\testfolder\file-100.txt
C:\testfolder\file-101.txt
C:\testfolder\file-102.txt
What I was trying to do in VB is move text file file-100.txt to the 100 directory. Same for text file file-101.txt, move it to its pertaining folder 101.
My question is how can I write a loop so that my program matches part of the string of my text file name and move it to the matching folder name? Moving one file at a time wouldn't be effecient since I have hundreds of directories and files to apply this to.
Edit:
I'm somewhat familiar with VB. I was having trouble with the logical part of this, in which I couldn't think of a way to write a loop so that it can transfer the files for me.
Without error checking, this would be a simple routine to move those files. It's based on your file names being consistent:
Private Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Click
Dim homePath As String = "c:\testfolder"
Dim files() As String = Directory.GetFiles(homePath, "*.txt")
For Each f As String In files
Dim fileName As String = Path.GetFileName(f)
Dim destPath As String = Path.GetFileNameWithoutExtension(fileName)
destPath = destPath.Split("-")(1)
destPath = Path.Combine(homePath, destPath)
Dim destFile As String = Path.Combine(destPath, fileName)
File.Move(f, destFile)
Next
End Sub
This just gets the list of text files in your directory, parses the file name to get just the number value (100, 101, etc), and then reconstructs the new path. It assumes the directories exist, too.
You can use regular expression to find matched pattern
Dim dir As String = "C:\testfolder\"
Dim fileList() As String = {"C:\testfolder\file-100.txt", _
"C:\testfolder\file-101.txt", _
"C:\testfolder\file-102.txt"}
Dim pattern As New Regex(Replace(dir, "\", "\\") & "file-([0-9]+)[.]txt")
For Each value As String In fileList
Dim match As Match = pattern.Match(value)
If match.Success Then
MsgBox("move from " & dir & " to " & dir & match.Groups(1).Value)
End If
Next
Make sure you have import RegularExpressions.
Imports System.Text.RegularExpressions
Private Sub organizeFiles(ByVal folderPath As String)
For Each filePath As String In Directory.GetFiles(folderPath, "*.txt")
Dim destinationFilePath As String = getDestinationFilePath(filePath)
If destinationFilePath IsNot Nothing Then
File.Move(filePath, destinationFilePath)
End If
Next
End Sub
Private Function getDestinationFilePath(ByVal filePath As String) As String
Const fileNamePrefix As String = "file-"
Dim fileName As String = Path.GetFileName(filePath)
Dim fileNameWithoutExtension As String = Path.GetFileNameWithoutExtension(filePath)
If Not fileNameWithoutExtension.StartsWith(fileNamePrefix) Then
Return Nothing
End If
Dim folderName As String = fileNameWithoutExtension.Substring(fileNamePrefix.Length)
Dim fileFolderPath As String = Path.GetDirectoryName(filePath)
Dim destinationFolderPath As String = Path.Combine(fileFolderPath, folderName)
Dim destinationFilePath As String = Path.Combine(destinationFolderPath, fileName)
Return destinationFilePath
End Function
Lets say i have this in a shell
"chdir * && whoami.exe >> $$$"
I have this replacecommand
Dim ReplaceCommand as String = sCommand.Replace("*", UserDirect)
I also would like the $$$ to be replaced with a user chosen filepath.
I can get the file path chosen but it never puts it into the shell.
I have tried
Dim ReplaceCommand1, ReplaceCommand2 as String = sCommand.Replace("*" & "$$$", UserDirect & filepath)
Shell("cmd.exe" & ReplaceCommand1 & ReplaceCommand2)
Dim ReplaceCommand as String = sCommand.Replace("*", UserDirect) & ("$$$", filepath)
Shell("cmd.exe" & ReplaceCommand)
also
Dim ReplaceCommand1 as String = sCommand.Replace("*", UserDirect)
Dim ReplaceCommand2 as String = sCommand.Replace("$$$", filepath)
Shell("cmd.exe" & ReplaceCommand1 & ReplaceCommand2)
EDIT:
get a path to short error when I use commas in shell instead of &
Dim ReplaceCommand1 as String = sCommand.Replace("*", UserDirect)
Dim ReplaceCommand2 as String = sCommand.Replace("$$$", filepath)
Shell("cmd.exe", ReplaceCommand1 , ReplaceCommand2)
You can chain the Replace's together:
Dim ReplaceCommand1 as String = sCommand.Replace("*", UserDirect).Replace("$$$", filepath)
Shell("cmd.exe" & ReplaceCommand1)
Part of your examples don't compile cause of the syntax errors.
You're not using Shell() like you're supposed to.
Public Function Shell(
PathName As String,
Optional Style As Microsoft.VisualBasic.AppWinStyle = MinimizedFocus,
Optional Wait As Boolean = False,
Optional Timeout As Integer = -1
) As Integer
From the examples you gave, it looks like you're just throwing stuff together. Stop and think for a minute :)