.NET Tutorials, Forums, Interview Questions And Answers
Welcome :Guest
Sign In
Win Surprise Gifts!!!

Top 5 Contributors of the Month
david stephan
Gaurav Pal
Post New Web Links

Random line from a text file

Posted By:      Posted Date: September 21, 2010    Points: 0   Category :.NET Framework


Im trying to pull a random line from a text file and store it into a variable.

I found this piece of code on the web which looks good but I cant seem to get it working in vs 2010, any ideas ?

Dim MyString As String
Dim MyBuffer() As Byte
Open "C:\AFile.txt" For Binary Access Read As #1
  ReDim MyBuffer(LOF(1) - 1)
  Get 1, , MyBuffer
  MyString = StrConv(MyBuffer, vbUnicode)
  ReDim MyBuffer(0) 'Free up memory
Close #1

Many thanks in advance.


View Complete Post

More Related Resource Links

Deleting Last Line of Text in a text file

Hi, I needed some help on the best way to delete the last line of  text in a text file. I have a subroutine that looks like this, but it is missing some code. Could anyone advise me on this? Dim strLogFile As String = System.Web.HttpContext.Current.Server.MapPath("~/Log.txt")         Dim fs As New FileStream(strLogFile, FileMode.Open, FileAccess.ReadWrite, FileShare.None)         Dim swLog As New StreamReader(fs)         Dim array As String()         Dim value As String = swLog.ReadToEnd ''Array that holds the lines of the text file.         array = value.Split(vbCrLf)        ''code for deleting last line: . . .  fs.Close()

How to read/write GIANT text file with no line breaks


I have to process giant XML files that are 6GB+ in size.  The problem is that there are no line breaks in the file, and the XML is improperly formatted (no root element).  Therefore I can't use the XML class to read the file, and I can't open the file in any text editor or even "Type" it in a command window because the 1 line in the file is over 6GB.

The file contains UTF8 characters.  What I want to do is first write a program just to read and display 100 characters at a time so I can look at the contents.  Next I want to be able to create a new file, write a root element, read/write the contents of the file and then write the closing root element.

Can anyone provide a code snippet of how to read and display the file contents 100 characters at a time.  I can then figure out the rest.


How to delete a line from a text file using C#

Hello all

I am developing a little app where I need to monitor a file that is update by several machines.

I need to gather each line wrote by each machine so I need access to a specific line number and take that line, store it into a DB table and delete that line.

I really don't know how to delete the line without parse the information into a string variable and rewrite the file. This can lake the app because the file can contain up to 1000K lines... :-O...

Any suggestion will be appreciated.

I think I deleted the Internet...

Removing blank line from a text file


Hi i have a comma deliminated text file which i am using to generate a multidimensional array using the following code:

Dim DefinitiveDatabase As String(,)
    Dim strfilename As String = (Server.MapPath("~\Definitive database.txt"))
    Dim num_rows As Long
    Dim num_cols As Long
    Dim x As Integer
    Dim y As Integer
    Dim value As Integer
    Dim ConditionName As String
    Dim strlines() As String
    Dim strline() As String
    Dim tmpstream As StreamReader = File.OpenText(strfilename)

strlines = tmpstream.ReadToEnd().Split(Environment.NewLine)
        num_rows = UBound(strlines)
        strline = strlines(0).Split(",")
        num_cols = UBound(strline)
        ReDim DefinitiveDatabase(num_rows, num_cols)
        For x = 0 To num_rows
            strline = strlines(x).Split(",")
            For y = 0 To num_col

How to speed up Reading Text File line by line?


Hi all,

The following is my problem which need to be solved:


I have text file like this:

id=1, name=smith, age=22, address=London;

id=2, name=john, age=30, address=Roma;

id=3, name=Pen, age=19, weight=60, address=Paris;

id=4, name=Ajay, age=44, address=India;


using vb, I succeeded to convert it to a table format like this


id      name        age       weight      address

1      smith          22           null         London

2      john            30          null          Roma

3      pen             19           60           Paris

4      Ajay            44           null          India


I used StreamReader for that.

someone may still ask: Ok Adel so where is your problem? kindly read the following lines

In fact, my only problem is related to the time it takes if the number of rows is 70,000

New off line application working with sdf file. Need advice


Hey Folks

I am working on a project currently where I need to get data out of a 3rd party vendor's software that uses a .sdf file I looked this up and its a SQL CE file. I was hoping to just link to with with access but thats apparently not going to happen. I need to link to the database extract data from it to a csv file for later use. I also and most important I need to get the data from it and create a report that can be printed while on a customers site that my or may not have web access so I need for this program to be on and off line. I had my webapplication that I have been working on open and was able to bring up the sdf file under the server exploere however I can't seem to get anything out of it when I try to do grid views or detail views errors out.

Can I use one of Visual Studio projects to create this sort of applicaiton if so what would be the best approach. I would love to get an access odbc driver since office is allready installed on the employee's laptop's



Writing to a text file



I have the following  subroutine in an asp.net application class. The subroutine writes data to a text file upon application login.   My question is that if this function was called at the same time by two different  users would it cause any kind of error. Is there a need for a try catch?

 Public Shared Sub writeToLogFile(ByVal UserName  As String)
        Dim strLogMessage As String = String.Empty
        Dim strLogFile As String = System.Web.HttpContext.Current.Server.MapPath("~/Log.txt") Dim swLog As StreamWriter
        strLogMessage = DateTime.Now.ToShortDateString().ToString()  " ==> " & UserName

        If Not File.Exists(strLogFile) Then
            swLog = New StreamWriter(strLogFile)
            swLog = File.AppendText(strLogFile)
        End If


The file reached the maximum download limit. Check that the full text of the document can be meaning



I'm facing an issue with the indexing.

I have 1 WFE+Index server+DB server.

Index server is not installed with MS FIlter pack 1.0

When crawling, the there will be document with warning in crawl log:
The file reached the maximum download limit. Check that the full text of the document can be meaningfully crawled.

Documents that with warning are such as doc, ppt, xls, docs, ppts and many others.
However, I view into the successful crawled document, there are doucments with ext doc and ppt.

For large file index, there are MaxGrowthFactor + MaxDownLoadSize required to be added into the index server.

As my understanding is, MS Filter Pack should installed into index server(already did, correct me if i'm wrong).

I looked into the Office SharePoint Seach(CA>Services in farm), if the server is appointed to "Use this server as indexing server", then MS Filter Pack is suppose to be installed into that particular server as well.

At the bottom, there also has another option is "Use all web front end for crawling".

The question here is, IF the option "Use all web front end for crawling" is selected.
Does the WED FRONT END Server required to installed the Ms Filte

Update Profile Database from text file using BDC



I have a requirement to import the profile properties from a text file in sFTP to update the MOSS Profile Database. The objective is to create a single repository for the Staff Directory in MOSS.

Can I use BDC to connect and update the Profile database?

What is the alternate approach?


Mission Impossible? Use Javascript to Disable a Multi-Line Rich Text Field


Hey Community,

Here's a tough one that I have struggled with and so far have not been able to find an answer for - how do you use Javascript to disable a multi-line rich text field.  I have customized a SP Edit form by adding a CEWP.  In the CEWP I have added the Javascript below (only a partial code sample provided) to disable several fields in the form.  The code works fine for single line text fields but it does not work for multi-line rich text fields.  Any suggestions?

<script language="javascript">
//This runs the function when the form first loads

//This locks the fields the users should not modify
function lockFields()
  var theInputTFTitle = getTagFromIdentifierAndTitle("Input","TextField","Title");
  theInputTFTitle.readOnly = true;
  theInputTFTitle.style.color = 'gray';
  //alert(" Value: " + theInputTFTitle.value);//for testing

   var theInputDDLReplyStatus = getTagFromIdentifierAndTitle("select","DropDownChoice","Reply Status");
  theInputDDLReplyStatus.disabled = true;
  //alert(" Value: " + theInputDDLReplyStatus.value);//for testing

  var theInpu

Data loading from text file

Hi, I am loading the data from a flat file into a sql table. The values in one of the column have spaces at the end of the value. I want to remove those spaces and load into the table. I am thinking of using derived column and use rtrim on that column, how can I use that as an expression. Thanks.sqldev

Consistently running out of page file memory with full text indexer

Using MS SQL Server 2008 SP1 x64 Standard Edtion on Windows 2008 R2 Enterprise, I'm about to full-text index for the first time 1 table and 2 views. The table contains about 250'000 entries with a data space of 180 MB. As soon as I activate the full text indexing, the fdhost.exe task starts to consume slowly but surely all the available page file space (this can be easily watched using the Resource Monitor and the Commit Charge graph on the memory tab). Once all the virtual memory has been consumed, the server becomes unusable since it can't open any new windows any more, and RDP stops working. The machine specs are as follows: 12 GB of RAM 80 GB free on hard disk out of 136 GB 8 CPUs Custom size paging file with sizes between 24 GB - 60 GB (originally, this was system managed size, but then the server ran out of memory sooner) Max SQL server memory set to 6 GB (first 10 GB, then 8 GB) I've set the max fulltext crawl range to 8. During the indexing, the 8 CPUs are bit busy for a while, but not excessively. What is astonishing is that there is almost no use of physical memory during the indexing (I can see an increase from 2 GB to 3 GB which still leaves plenty of RAM available). Does anybody have an idea how I can convince fdhost.exe to consume physical memory and leave the paging memory alone? Or what else can I try?

Read a text file on another server from a web page

How do I read/write a text file on another server from a web page. I get the error "Access to the path '//Server2/mydatafiles/test.txt' is denied". I do not get the error if I am running the browser on the server where the files exist. I think I need to set permissions on the destination server in some way.   Can you help? Thanks  

convert xml file as text file using xml document

hi i want to convert to xml file to text file using xml document.. M not much aware of xml..so please guide me.... my boss told me don use xmltextreader and using xml document convert to txt file.....  

How to put text from an external text file into a text box on a report.

Hi all, We're moving from our legacy reporting app to SQL Server Reporting Services 2008 and I'm converting our reports slowly but surely.  In our organization, one of our departments sends out letters that have standard marketing messages and disclaimers that they put into .rtf files.  Currently, our reporting application has an RTF box control that can do that fairly easily.  I've not found a similar control in SSRS 2008.  My thought, then, was to use a piece of embedded code in the report to grab the necessary text from the file and reference it in the Value of a Placeholder (using a Code.<FunctionName>.ToString() statement) - using HTML tags for the necessary formatting for those files. I don't care if I have to convert the existing RTF files to HTML files to do this, that's not an issue.  The code I'd come up with is this:  Public Function GetTextFile(ByVal strFileName as String) As String Dim oFile as System.IO.File Dim oRead as System.IO.StreamReader oRead = oFile.OpenText(strFileName) GetTextFile = oRead.ReadToEnd() End Function And the Expression I was using to get the text from the file is:  =Code.GetTextFile("HTMLTest.txt").ToString() Where "HTMLTest.txt" is the file name that I'm using.  The text itself is just a line of text with some HTML tags included for formatting - bold, color,

putting carriage return/line feed in non-HTML email text

Using vb.net/asp.net 2005I am trying to create a string message for an email that I am sending out from my asp.net page like so: For Each dr In dtDataTable.Rows strMessage = strMessage & vbCrLf & vbCrLf & Environment.NewLine & dr.Item("UserName") & Environment.NewLine Next so I am looping through a datatable and getting each name from each row, that is working well but when I get the email it appears in my inbox with all the names mashed together, you see I am trying both vbcrlf and newline but looks like neither is workingdoes anyone know what I'm doing wrong?

Saving SSIS results to Log or text file using dtexec

Hi, How to save the SSIS package results to log file using dtexec command............please help regaridng this...........   Thanks in advance,
ASP.NetWindows Application  .NET Framework  C#  VB.Net  ADO.Net  
Sql Server  SharePoint  Silverlight  Others  All   

Hall of Fame    Twitter   Terms of Service    Privacy Policy    Contact Us    Archives   Tell A Friend