my application is MVC3 C#; I am populating two dropdownlists using json using the following:
public ActionResult CheckWord(string cword)
{
try
{
List<string[]> arrayList = new List<string[]>();
List<string[]> stateList = new List<string[]>();
//
List<string[]> fileList = new List<string[]>();
//
string[] filePaths = Directory.GetFiles(System.Web.HttpContext.Current.Server.MapPath("/Video"), "*.srt");
string[] fnList = new string[filePaths.Length];
for (int i = 0; i < fnList.Length; ++i)
{
FileInfo fi = new FileInfo(filePaths[i]);
fnList[i] = fi.Name.Substring(0, fi.Name.LastIndexOf(".srt"));
}
int nFiles = filePaths.Length;
string cacheline = "";
string line;
for (int i = 0; i < nFiles; ++i)
{
StreamReader file = new StreamReader(System.Web.HttpContext.Current.Server.MapPath("/Video/" + fnList[i] + ".srt"));
List<string> lines = new List<string>();
List<string> statments = new List<string>();
//
List<string> fnames = new List<string>();
//
while ((line = file.ReadLine()) != null)
{
if (line.Contains(cword))
{
statments.Add(line);
// fnames.Add(file);
lines.Add(cacheline);
}
cacheline = line;
}
file.Close();
var array = lines.ToArray();
arrayList.Add(array);
stateList.Add(statments.ToArray());
}
return Json(new { success = true, fnList = fnList, arrayList = arrayList.ToArray(), stateList = stateList.ToArray() });
}
catch { }
return Json(new { success = false });
}
I am checking if a word exists in a group of files; then display the names of files in one dropdownlist and the lines from each file in the other dropdownlist. It works fine, however it gives me a list of all files becasue I am sending back fnlist. However I am trying to display only the files that contain that word; I could not get the file name from the StreamReader and add it to an array fileList. I would appreciate your suggestions, thanks in advance.
Already so many lists! Why not another? You already open the file with fnList[i] within the context of the loop, so...
List<string[]> results = new List<string[]>();
....
while ((line = file.ReadLine()) != null) {
if (line.Contains(cword)) {
results.Add(fnList[i]);
break; // optional, if possible, but if you need to continue check for dupes
}
}
....
return Json(new {
success = true,
fnList = results.ToArray(),
arrayList = arrayList.ToArray(),
stateList = stateList.ToArray()
});
System.IO.StreamReader file = new System.IO.StreamReader("setup.txt");
Later on, we would like to print the name of the file being used by stream reader.
eg, if there is an error, I would like a message box that displays "error reading file: 'filename'"
MessageBox.Show("Error loading " + ((FileStream)file.BaseStream).Name);
Not sure what exactly you are looking for but since you are creating StreamReader from a file name why not have file name in a separate variable and use it later:
var fileName = System.Web.HttpContext.Current.Server.MapPath(
"/Video/" + fnList[i] + ".srt");
StreamReader file = new StreamReader(fileName);
Related
I watch a lot of tutorials on how to delete a certain row in Excel.
Please help mo to delete a row in excel using c#.
The fileReader ,FileWriter and Splitter are already working. My only problem now is how to delete a certain row in Excel.
Class Variable
public static string fileName = #".\Contestant.csv";
public static string[,] contestant;
Main Method
List<string> lines = fileReader(fileName);
while (i < lines.Count)
{
string[] temp = stringSplitter(lines[i], new char[] { ',' });
// a contains how many elements in the array
a = temp.Count();
// divides a and plus by 1 to know how many arrays there should be in the 2d array
d = (a / 2) + 1;
contestant = new string[a, d];
This is my code for FileReader
static List<string> fileReader(string filePath)
{
List<string> lines = new List<string>();
try
{
using (StreamReader sr = new StreamReader(filePath))
{
string line = "";
while ((line = sr.ReadLine()) != null)
{
lines.Add(line);
}
}
}
catch (Exception e)
{
Console.WriteLine("Error Message: Please close the file and try again");
//Console.WriteLine(e); for more detailed errors
}
return lines;
}
Here's my code for FileWriter
static void fileWriter(string filePath, bool appendFlag, string message)
{
using (StreamWriter sr = new StreamWriter(filePath, appendFlag))
{
sr.WriteLine(message);
}
}
This is for Splitter String
static string[] stringSplitter(string stringToSplit, char[] splitChars)
{
return stringToSplit.Split(splitChars);
}
I would recommend to completely manipulate your date inside the lists, then replace the whole document with the new information. So read all -> manipulate -> replace your document with new content.
Also don't forget to close your FileStreams after reading/writing.
I am currently using the below code to compare two csv files with each other. This code gives an output with all the rows that are not the same. But when a row is missing everything after that row is not the same. How can I fix this? Thanks in advance.
List<string> lines = new List<string>();
List<string> lines2 = new List<string>();
try
{
StreamReader reader = new StreamReader(System.IO.File.OpenRead(file1));
StreamReader read = new StreamReader(System.IO.File.OpenRead(file2));
List<string> differences = new List<string>();
string line;
string line2;
int i = 0;
while ((line = reader.ReadLine()) != null && (line2 = read.ReadLine()) != null)
{
string[] split = line.Split(Convert.ToChar("\t"));
string[] split2 = line2.Split(Convert.ToChar("\t"));
if (split[i] != split2[i])
{
differences.Add("this row is not the same:, " + line);
}
else
{
}
i++;
}
System.IO.File.WriteAllLines(differencesFile, differences);
reader.Dispose();
read.Dispose();
}
catch
{
}
After help from a friend I made it work with this code:
List<string> file1 = new List<string>();
List<string> output = new List<string>();
string differencesFile = path;
File.WriteAllText(differencesFile, "");
try
{
StreamReader readFile1 = new StreamReader(System.IO.File.OpenRead(pathfile1));
string lineFile1;
while ((lineFile1 = readFile1.ReadLine()) != null)
{
bool match = false;
string[] colums = lineFile1.Split('\t');
StreamReader readFile2 = new StreamReader(System.IO.File.OpenRead(pathfile2));
string line2;
while ((line2 = readFile2.ReadLine()) != null)
{
string[] columsFile2 = line2.Split('\t');
if (colums[0] == columsFile2[0])
{
match = true;
}
}
if (!match)
{
output.Add(colums[0] + "; doesnt exist in pathfile2");
}
}
System.IO.File.WriteAllLines(differencesFile, output);
}
catch { }
I have a file that I need to save as an array. I am trying to convert a text file to an integer array using StreamReader. I just am unsure as to what to put in the for loop at the end of the code.
This is what I have so far:
//Global Variables
int[] Original;
//Load File
private void mnuLoad_Click_1(object sender, EventArgs e)
{
//code to load the numbers from a file
OpenFileDialog fd = new OpenFileDialog();
//open the file dialog and check if a file was selected
if (fd.ShowDialog() == DialogResult.OK)
{
//open file to read
StreamReader sr = new StreamReader(fd.OpenFile());
int Records = int.Parse(sr.ReadLine());
//Assign Array Sizes
Original = new int[Records];
int[] OriginalArray;
for (int i = 0; i < Records; i++)
{
//add code here
}
}
The .txt file is:
5
6
7
9
10
2
PS I am a beginner, so my coding skills are very basic!
UPDATE: I have previous experience using Line.Split and then mapping file to arrays but obviously that does not apply here, so what do I do now?
//as continued for above code
for (int i = 0; i < Records; i++)
{
int Line = int.Parse(sr.ReadLine());
OriginalArray = int.Parse(Line.Split(';')); //get error here
Original[i] = OriginalArray[0];
}
You should just be able to use similar code to what you had above it:
OriginalArray[i] = Convert.ToInt32(sr.ReadLine());
Every time the sr.ReadLine is called it increments the data pointer by 1 line, hence iterating through the array in the text file.
try this
OpenFileDialog fd = new OpenFileDialog();
if (fd.ShowDialog() == DialogResult.OK)
{
StreamReader reader = new StreamReader(fd.OpenFile());
var list = new List<int>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
int value = 0;
if (!string.IsNullOrWhiteSpace(line) && int.TryParse(line, out value))
list.Add(value);
}
MessageBox.Show(list.Aggregate("", (x, y) => (string.IsNullOrWhiteSpace(x) ? "" : x + ", ") + y.ToString()));
}
You can read the entire file into a string array, then parse (checking the integrity of each one).
Something like:
int[] Original;
//Load File
private void mnuLoad_Click_1(object sender, EventArgs e)
{
//code to load the numbers from a file
var fd = new OpenFileDialog();
//open the file dialog and check if a file was selected
if (fd.ShowDialog() == DialogResult.OK)
{
var file = fd.FileName;
try
{
var ints = new List<int>();
var data = File.ReadAllLines(file);
foreach (var datum in data)
{
int value;
if (Int32.TryParse(datum, out value))
{
ints.Add(value);
}
}
Original = ints.ToArray();
}
catch (IOException)
{
// blah, error
}
}
}
Another way to do it if you'd like to read to the end of the file and you don't know how long it is with a while loop:
String line = String.Empty;
int i=0;
while((line = sr.ReadLine()) != null)
{
yourArray[i] = Convert.ToInt32(line);
i++;
//but if you only want to write to the file w/o any other operation
//you could just write w/o conversion or storing into an array
sw.WriteLine(line);
//or sw.Write(line + " "); if you'd like to have it in one row
}
//using linq & anonymous methods (via lambda)
string[] records = File.ReadAllLines(file);
int[] unsorted = Array.ConvertAll<string, int>(records, new Converter<string, int>(i => int.Parse(i)));
So, I know my headline is a bit confusing, I will explain.
My code looks like this:
string filename = "C:\\C#\\maplist.txt"; // please put the text file path.
string filename2 = "C:\\C#\\zemaplist.txt";
string map;
StreamReader sr = new StreamReader(filename);
StreamWriter sw = new StreamWriter(filename2);
List<string> maps = new List<string> { };
while ((map = sr.ReadLine()) != null)
{
maps.Add(map);
}
sr.Close();
for (int i = 0; i < maps.Count; i++)
{
Console.WriteLine(maps[i]);
sw.WriteLine(maps[i]);
}
sw.Close();
and what i need to do is when the code read a new line, in my line there is
"Hey,Hey"
I want to split the , from each other so I can take both of them as other parameters, so that the first Hey will be added to maps and the other hey will be maps2,
How can I do that?
You can use Split() function to Split the given String based on delimiter.
Try This:
while ((map = sr.ReadLine()) != null)
{
maps.Add(map.Split(',')[0].Trim());
maps2.Add(map.Split(',')[1].Trim());
}
Simple Code:
using System.IO;
string filename = "C:\\C#\\maplist.txt"; // please put the text file path.
string filename2 = "C:\\C#\\zemaplist.txt";
string map;
StreamWriter sw = new StreamWriter(filename2);
List<string> maps = new List<string> { };
List<string> maps2 = new List<string> { };
String [] allLines = File.ReadAllLines(filename);
foreach(String line in allLines)
{
maps.Add(line.Split(',')[0].Trim());
maps2.Add(line.Split(',')[1].Trim());
}
for (int i = 0; i < maps.Count; i++)
{
Console.WriteLine(maps[i]);
sw.WriteLine(maps[i]);
}
sw.Close();
Solution 2:
String mapItem1="";
String mapItem2="";
if(maps.Count == maps2.Count)
{
for(int i=0;i<maps.Count;i++)
{
mapItem1=maps[i];
mapItem2=maps2[i];
}
}
while ((map = sr.ReadLine()) != null)
{
string[] split = map.Split(',');
//First Hey would be split[0], second Hey would be split[1]
maps.Add(split[0].Trim());
maps2.Add(split[1].Trim());
}
The Split method should help you out with that.
If you want to trim leading whitespace characters, you can use the .Trim() method on a string.
Use Split().
string heys = "Hey,Hey";
string[] splitArray = heys.Split(',');
Then you have:
splitArray[0] = "Hey";
splitArray[1] = "Hey";
Why even bother reading line by line? Read the entire file, replace the new line chars for a "," (to prevent last and first elements from different lines to be treated as one), and loop through a clean string.
string fileContent = Regex.Replace(File.ReadAllText("test.txt"), #"\r", ",");
List<string> mapList = new List<string>();
foreach (string map in Regex.Split(fileContent.Replace(#"\s+", ""), ","))
{
mapList.Add(map.Trim());
}
Below is my code. I have multiple webpages, and I need to save all these webpages sources codes to one txt file, is it possible? My code is saving just one webepage source, I can choose which one to save by changing number in that part of code:
string s=WebClient.DownloadString(listBox8.Items[0].ToString());
In listbox8 there is multiple webpages adresses. Those addresses are taken from tvrage_db2.txt file.
Can you help me?
List<string> link = new List<string>();
using (StreamReader sr = new StreamReader("tvrage_db2.txt"))
{
string line;
//Read and display lines from the file until the end of the file is reached
while ((line = sr.ReadLine()) != null)
{
string line2 = line;
link.Add(line2);
}
}
listBox8.DataSource = link;
using (WebClient WebClient = new WebClient())
{
for (int i = 0; i < listBox8.Items.Count; i++)
{
string s = WebClient.DownloadString(listBox8.Items[0].ToString());
Clipboard.SetText(s, TextDataFormat.Text);
string[] lines = { s };
System.IO.File.WriteAllLines(#"WriteLines.txt", lines);
}
}
}
EDIT:
Problem solved
using (WebClient WebClient = new WebClient())
{
for (int i = 0; i < listBox8.Items.Count; i++)
{
string s = WebClient.DownloadString(listBox8.Items[i].ToString());
string[] lines = { s };
System.IO.File.AppendAllText(#"WriteLines.txt", lines[0]);
}
}
You're already looping listBox8 items, so change
string s = WebClient.DownloadString(listBox8.Items[0].ToString());
to
string s = WebClient.DownloadString(listBox8.Items[i].ToString());