C#/reading a text file
Expert: Srini Nagarajan - 2/5/2008
QuestionQUESTION: Please help me to complete the below script so that i can read a text file called new from my C drive
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "
http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@ Import Namespace="System.IO" %>
<script language="C#" runat="server" >
private void Button1_Click(object sender, System.EventArgs e)
{
StreamReader fp;
fp = File.OpenText(Server.MapPath("new.txt"));
TextBox1.Text = fp.ReadToEnd();
fp.Close();
}
</script>
<html xmlns="
http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<span
style="font-size: 9pt; font-family: Verdana">Reading Data from a Text File in ASP
.NE
<asp:TextBox ID="TextBox1" runat="server" Style="z-index: 100; left: 77px; position: absolute;
top: 99px" TextMode="MultiLine"></asp:TextBox>
T
<asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Style="z-index: 102;
left: 78px; position: absolute; top: 176px" Text="Button" />
</span>
</div>
</form>
</body>
</html>
ANSWER: hi
Change the following line to the way i recommended.
Change from
fp = File.OpenText(Server.MapPath("new.txt"));
Change to
fp = File.OpenText(Server.MapPath("c:\\new.txt"));
-Srini
---------- FOLLOW-UP ----------
QUESTION: I tried with it but no use.. It throws a exception saying that the virtual path does not exist. I have a file created in my C drive with the name new.txt.
ANSWER: my bad.. Try this!!
fp = File.OpenText("c:\\new.txt");
-Srini
---------- FOLLOW-UP ----------
QUESTION: No use.. the file cant be found is the new error.
AnswerHi
Check whether you have given permission, Here is the working script
1st step it checks for file exists and create the text file
2nd step it reads from the file.
-Srini
using System;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
string path = @"c:\temp\MyTest.txt";
// Delete the file if it exists.
if (!File.Exists(path))
{
// Create the file.
using (FileStream fs = File.Create(path))
{
Byte[] info =
new UTF8Encoding(true).GetBytes("This is some text in the file.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
}
// Open the stream and read it back.
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
}