how to read twice a file using fileupload - c#

I am trying to read the same file twice.
I have been using a FileUpload to look up the file. I was successful in the first read where I find out how many lines the file have, using the next code in C# ans asp.net:
Stream data_file;
data_file=FileUpload1.PostedFile.InputStream;
string line;
int elements;
StreamReader sr = new StreamReader(data_file);
line = sr.ReadLine();
while (line != null)
{
elements = elements + 1;
line = sr.ReadLine();
}
sr.Close();
With this number I can now create an array of array by setting fist how many elements the array is going to hold. The array this time is going to hold the number from the file something like this:
datafile:
1,1
2,3
arrayL[0][0]=1
arrayL[0][1]=1
arrayL[1][0]=2
arrayL[1][0]=3
so the code to do this is the next:
double [][] dime= new double [elements][];
string[] div;
string line2;
int nn=0;
StreamReader ssr = new StreamReader(data_file);
line2 = ssr.ReadLine();
while (line2 != null)
{
dimen[nn] = new double[2];
for (int m2 = 0; m2 < 2; m2++)
{
div=line2.Split(new Char[] { ' ', ',', '\t' });
dimenc[nn][m2] = Convert.ToDouble(div[m2]);
}
nn=nn+1;
line2 = ssr.ReadLine();
}
ssr.Close();
However, the array says that it is empty but I know if I used the second part of the code in a complete diferrent method/ second button but if it is in the same method it does not work so my question is:
What's wrong? Why the second streamreader is not working?

Actually #NLemay comment is probably the better solution.
But in the case someone would need to read an uploaded file twice, you would need to cache the file in memory. Either read the stream into a byte[] or a MemoryStream then work your streamreader from that. You'll find that HttpPostedFile.InputStream.CanSeek is false, which is what you're trying to do.
For a byte[]:
HttpPostedFile uFile = uploadFile.PostedFile;
byte[] data = new byte[uFile.ContentLength];
uFile.InputStream.Read(data, 0, uFile.ContentLength);
For a MemoryStream look up a CopyStream method.

Related

How can I read a text file and write its values to an array

I have a text file with values and I need to read them. The first line is the size of my array and the second line has values that I need to put into to an array.
My main looks like:
public static void Main()
{
int n,i=0,k=1;
var plik_wejsciowy = new StreamReader("In0201.txt");
StreamWriter plik_wyjsciowy = new StreamWriter("Out0201.txt");
string[] wejscie = plik_wejsciowy.ReadLine().Split(' ');
n = int.Parse(wejscie[0]);
int[] tab = new int[n];
for (i=0;i<n;i++)
{
tab[i] = int.Parse(wejscie[k]);
k++;
}
plik_wyjsciowy.Close();
}
I don't really know what to do and where I'm making a mistake.
We can make life easier; you don't really need to use the first line to track how many lines are in the file; you can just read the lines into an array (skip the first if it's only a line counter) then parse the rest and turn them into an array:
var x = File.ReadAllLines(path).Skip(1).Select(int.Parse).ToArray();
If you switch the first line being a counter of lines, remove the Skip(1)

Updating line of a file if array element matches text box

I have a method which currently reads all lines of a directory file (3 fields per line) and updates a directory array with a record of text box entries if the extension code entered matches an extension code field in the file.
I had the updated directory array displaying to a list view, as soon as I attempted to update the directory file with the updated array, it all went downhill! Edit to clarify: with the latest version of the code below, the array no longer displays to the list view, and the file is not updated. No errors are thrown.
public void updateName()
{
int count = 0;
string[] lines = File.ReadAllLines(directoryFile);
// Set size of directory array equal to number of lines in file
int lineCount = lineCounter();
directory = new record[lineCount];
record currentRecord = new record();
// Iterate through each line in file
foreach (string line in lines)
{
// Split current line into three fields
string[] fields = line.Split(',');
// Save current line as new record with surname, forename and extCode fields
currentRecord.surname = fields[0];
currentRecord.forename = fields[1];
currentRecord.extCode = Convert.ToInt32(fields[2]);
// If extension code in current record matches text box entry
if (Convert.ToInt32(fields[2]) == Convert.ToInt32(txtExtCode.Text))
{
// Change surname and forname fields to match text box entries
currentRecord.surname = txtForename.Text;
currentRecord.forename = txtSurname.Text;
using (StreamWriter writer = new StreamWriter(directoryFile))
{
for (int currentLine = 1; currentLine <= lines.Length; ++currentLine)
{
if (currentLine == count)
writer.WriteLine(currentRecord);
else
writer.WriteLine(lines[currentLine - 1]);
}
}
}
// Save currentRecord as next element in directory array, then increment
directory[count] = currentRecord;
count++;
}
}
You don't need a linecounter(). The number of lines is lines.Length.
But why do you need this directory array? You are filling it, but you are not using it anywhere.
Another major problem is that you are creating a StreamWriter inside the foreach loop. You should open the file before the loop and close it after the loop to make it work.
Also, you are mixing writing currentRecord which is of type record and writing lines of type string to the output file. This cannot work.
You are also putting txtForename.Text into currentRecord.surname instead of currentRecord.forename and vice versa.
I suggest to first apply the change in the lines array and then to write this lines array back to to file with File.WriteAllLines which is the symmetric operation to File.ReadAllLines.
I'm applying the change directly to fields array, so that I can convert it back to a string with String.Join (it is the symmetric operation to String.Split).
public void updateName()
{
// Do this conversion before the loop. We need to do it only once.
int selectedCode = Convert.ToInt32(txtExtCode.Text);
string[] lines = File.ReadAllLines(directoryFile);
for (int i = 0; i < lines.Length; i++)
{
// Split current line into three fields
string[] fields = lines[i].Split(',');
int extCode = Convert.ToInt32(fields[2]);
if (extCode == selectedCode)
{
fields[0] = txtSurname.Text;
fields[1] = txtForename.Text;
lines[i] = String.Join(",", fields);
// If the extension code is unique, leave the for-loop
break;
}
}
File.WriteAllLines(directoryFile, lines);
}
I also use for instead of foreach in order to have an index i, so that I can replace a single line in the lines array at a specific index.
I don't know if the extension code in the directory file is unique. If it is, you can exit the for loop prematurely with break.

Delete, copy, and paste string in an array in a text file to a new arry in a text file

I need some help with file streaming. I have a program that will record names into a string array that will be written to a .txt file. Then if a user wants to delete a specific string from the array in the .txt file. the program will search for the string in the array in the .txt file, copy all the lines in the .txt file except the matching string. Then, paste all of the lines in a temp .txt file except the 1 matching string. Then copy and paste all of the string lines in the temp .txt file back to the original .txt file and then delete the temp file.
The issue that i am having is, i can't figure out how to copy all of the string lines to the temp .txt file. I know that they are not getting copied because i am use a listbox (for diagnostic reasons) to output everything in the temp file, but nothing ever get displayed. I even F8 through the whole process and it seems like its writing, but it really isnt. I cant even start thinking about the rest of the programing until this part is solved and i need to know why it isnt writing to the temp file. Any help you provide would be really help. Thank you again.
string[] names = File.ReadAllLines("name.txt");
string fullName, firstName, lastName;
fullName = tbInput.Text.ToUpper();
double Fullname;
int space;
int fullNameLength;
if (fullName.Contains(" "))
{
//This is for the Last name//
space = fullName.IndexOf(" ");
fullNameLength = fullName.Length;
space++;
lastName = fullName.Substring(space, fullNameLength - space);
//This is for the first name//
firstName = fullName.Substring(0, space);
fullName = lastName + "," + firstName;
//If the input name is valid, then it will procceed to the next if statment//
Array.Sort(names);
//if the fullname matches a string in the array, get the position. If no match is found then name was never recorded//
int Position = Array.IndexOf(names, fullName);
//Since arrays start at 0, if a position is found, the position WILL be greater than -1, so run the if statment//.
if (Position > -1)
{
//Please ingnore these 2 lines, these are a work in progress for when i can move onto the next step of deletion and what not.//
// FileStream name = new FileStream("name.txt", FileMode.Open, FileAccess.Write);
//StreamWriter write = new StreamWriter(name);
//I want to Open the Temps.txt file and seek the last line in the file to indicate where it need to write the next string//
//while looping through the array "names"//
for (int i = 0; i < names.Length; i++)
{
//While looping through the array, "i" will increase by 1 each time the loop runs, when "i" equals the position(or index)//
//skip it. For everything else, read the line of the current index in the arry and write it to the temp.txt file//
if (i == Position)
{
names.Skip(Position);
}
else
{
FileStream sw = new FileStream("Temp.txt", FileMode.Append, FileAccess.Write);
StreamWriter write2 = new StreamWriter(sw);
string input = names[i];
write2.WriteLine(input);
sw.Close();
}
}
//This part is used to loop through the temp file and output to a temp listbox to see if data is actually writing//
string[] Temp = File.ReadAllLines("Temp.txt");
for (int j = 0; j < Temp.Length; j++)
{
lbtest.Items.Add(Temp[j]);
}
I added many comments so everyone can get something of an understanding of my thought process.
Why bother with the temp file? Since you're doing a File.ReadAllLines() store that result in a List<string>. Perform an IndexOf() check is in the List and remove it if it's greater than -1 (You're doing that with your Position variable). Then use File.WriteAllLines() and give it your list.
List<string> names = new List<string>(File.ReadAllLines("name.txt"));
string fullName = tbInput.Text.ToUpper();
int fullNameIndex = names.IndexOf(fullName);
if (fullNameIndex > -1)
{
names.RemoveAt(fullNameIndex);
}
File.WriteAllLines("name.txt", names);

reading string each number c#

suppose this is my txt file:
line1
line2
line3
line4
line5
im reading content of this file with:
string line;
List<string> stdList = new List<string>();
StreamReader file = new StreamReader(myfile);
while ((line = file.ReadLine()) != null)
{
stdList.Add(line);
}
finally
{//need help here
}
Now i want to read data in stdList, but read only value every 2 line(in this case i've to read "line2" and "line4").
can anyone put me in the right way?
Even shorter than Yuck's approach and it doesn't need to read the whole file into memory in one go :)
var list = File.ReadLines(filename)
.Where((ignored, index) => index % 2 == 1)
.ToList();
Admittedly it does require .NET 4. The key part is the overload of Where which provides the index as well as the value for the predicate to act on. We don't really care about the value (which is why I've named the parameter ignored) - we just want odd indexes. Obviously we care about the value when we build the list, but that's fine - it's only ignored for the predicate.
You can simplify your file read logic into one line, and just loop through every other line this way:
var lines = File.ReadAllLines(myFile);
for (var i = 1; i < lines.Length; i += 2) {
// do something
}
EDIT: Starting at i = 1 which is line2 in your example.
Add a conditional block and a tracking mechanism inside of a loop. (The body of the loop is as follows:)
int linesProcessed = 0;
if( linesProcessed % 2 == 1 ){
// Read the line.
stdList.Add(line);
}
else{
// Don't read the line (Do nothing.)
}
linesProcessed++;
The line linesProcessed % 2 == 1 says: take the number of lines we have processed already, and find the mod 2 of this number. (The remainder when you divide that integer by 2.) That will check to see if the number of lines processed is even or odd.
If you have processed no lines, it will be skipped (such as line 1, your first line.) If you have processed one line or any odd number of lines already, go ahead and process this current line (such as line 2.)
If modular math gives you any trouble, see the question: https://stackoverflow.com/a/90247/758446
try this:
string line;
List<string> stdList = new List<string>();
StreamReader file = new StreamReader(myfile);
while ((line = file.ReadLine()) != null)
{
stdList.Add(line);
var trash = file.ReadLine(); //this advances to the next line, and doesn't do anything with the result
}
finally
{
}

C# read in file using hex prints FFFFFF

very confused by this, when I read in a file using the code below when it gets to the end it prints out FFFFFF, could anyone explain this to me the text file only has numbers and letters in it? Any help would be most greatful!
String fileDirectory = "C:\\t.txt";
StreamReader reader = new StreamReader(fileDirectory);
int hexIn;
for (int i = 0; (hexIn = reader.Read()) != -1; i++)
{
String s;
s = hexIn.ToString("X2");
int x = 0;
while (x < 1)
{
hexIn = reader.Read();
s = hexIn.ToString("X2");
x++;
}
hexIn = reader.Read();
s = hexIn.ToString("X2");
MessageBox.Show(s);
}
You've got three Read calls per loop iteration, which means that any one of them could return -1 to indicate the end of the file. I suspect that's then being converted to FFFFFFFF, hence your output. Why do you have more than one Read call? And why aren't you reading a block at a time?
The FFFFFF may also indicate an empty value. If you Hex editted Nintendo DS Roms you would see a whole bunch of FFFFFFFF at the end which is put there because the game is too small for the cartridge so in actual fact that file may have empty values at the end.

Categories