I know this has been discussed many times on here, I've tried to set my variables as public etc. but I can't seem to be able to use it in my other name space. I'd appreciate if you could give me some tips (I'm a noob at C#)
The string i'm trying access from my other name space is "stringatlinei"
using System;
using System.Diagnostics;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Security;
using System.Security.Cryptography;
using System.IO;
using System.Net;
using Microsoft.Win32;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Net.Mail;
using ConsoleApplication32;
namespace ConsoleApplication32
{
public class Program
{
static void Main(string[] args)
{
DirSearch(#"C:\\Users\\");
Console.ReadKey();
}
static void DirSearch(string dir)
{
try
{
foreach (string d in Directory.GetDirectories(dir))
{
Console.WriteLine(d);
DirSearch(d);
// Compose a string that consists of three lines.
string lines = d;
// Write the string to a file.
System.IO.StreamWriter file = new
System.IO.StreamWriter("c:\\users\\chris\\desktop\\test.txt", true);
file.WriteLine(lines);
file.Close();
var oldLines = System.IO.File.ReadAllLines("c:\\users\\chris\\desktop\\test.txt");
var newLines = oldLines.Where(line => !line.Contains("Windows"));
System.IO.File.WriteAllLines("c:\\users\\chris\\desktop\\test.txt", newLines);
var oldLines4 = System.IO.File.ReadAllLines("c:\\users\\chris\\desktop\\test.txt");
var newLines4 = oldLines.Where(line => !line.Contains("$Recycle.Bin"));
System.IO.File.WriteAllLines("c:\\users\\chris\\desktop\\test.txt", newLines4);
var oldLines7 = System.IO.File.ReadAllLines("c:\\users\\chris\\desktop\\test.txt");
var newLines7 = oldLines.Where(line => !line.Contains("Program Files"));
System.IO.File.WriteAllLines("c:\\users\\chris\\desktop\\test.txt", newLines7);
var oldLines8 = System.IO.File.ReadAllLines("c:\\users\\chris\\desktop\\test.txt");
var newLines8 = oldLines.Where(line => !line.Contains("Program Files (x86)"));
System.IO.File.WriteAllLines("c:\\users\\chris\\desktop\\test.txt", newLines8);
var oldLines9 = System.IO.File.ReadAllLines("c:\\users\\chris\\desktop\\test.txt");
var newLines9 = oldLines.Where(line => !line.Contains("AppData"));
System.IO.File.WriteAllLines("c:\\users\\chris\\desktop\\test.txt", newLines9);
}
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
}
var lineCount = File.ReadLines(#"c:\\users\\chris\\desktop\\test.txt").Count();
Console.WriteLine(lineCount);
Console.ReadLine();
int element = 0;
for (int i = 0; i < lineCount + 1; i++)
{
element = element + 1;
String stringAtLinei = File.ReadLines("c:\\users\\chris\\desktop\\test.txt").ElementAtOrDefault(element);
Console.WriteLine(stringAtLinei);
}
System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = "random command example thing";
process.StartInfo = startInfo;
process.Start();
}
}
}
then the other namespace etc.
"stringatlinei" is not a property, or a public anything, it is defined inside a loop inside a function.
Try public static string stringatlinei="", then just assign in your loop.
Accessing that variable in another namespace is not possible. You should read up on the basics, scope in particular, to understand why this is so. Here's a helpful article: https://msdn.microsoft.com/en-us/library/aa691132(v=vs.71).aspx
Basically, your variable you are trying access is created inside your for loop. Each iteration of your loop, it goes away.
Here's the part you should change: (I removed the rest for clarity)
namespace ConsoleApplication32
{
public class Program
{
public String stringAtLinei;
static void DirSearch(string dir)
{
for (int i = 0; i < lineCount + 1; i++)
{
stringAtLinei = File.ReadLines("c:\\users\\chris\\desktop\\test.txt").ElementAtOrDefault(element);
}
}
}
}
The point is that you can access fields and properties of a class, but not variables that are confined to the method they're in. So I changed the variable to be a field in the class.
Related
I am building a front end to parse some text files using Stanford Core NLP in C#. I open a file selection dialog and select some text files. Then the following method works from there on.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Text.RegularExpressions;
using java.util;
using java.io;
using edu.stanford.nlp.pipeline;
namespace Parser_SVO
{
public partial class Form1 : Form
{
public static List<string> textFiles = new List<string>();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.ShowReadOnly = true;
openFileDialog1.Filter = "Text Files|*.txt";
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
textFiles.AddRange(openFileDialog1.FileNames);
}
parseText();
}
public static void parseText()
{
label2.Text = "Stanford Parser....";
// Path to the folder with models extracted from `stanford-corenlp-3.7.0-models.jar`
string jarRoot = "";
string prettyPrint = "";
if (textFiles.Count != 0)
{
jarRoot = Path.GetDirectoryName(textFiles[0]) + #"\Models\";
prettyPrint = Path.GetDirectoryName(textFiles[0]);
Directory.CreateDirectory(prettyPrint + #"\PrettyPrint\");
prettyPrint = prettyPrint + #"\PrettyPrint\";
}
// Annotation pipeline configuration
var props = Properties();
props.setProperty("annotators", "tokenize, ssplit, pos, lemma, ner, parse, dcoref");
props.setProperty("ner.useSUTime", "0");
// We should change current directory, so StanfordCoreNLP could find all the model files automatically
var curDir = Environment.CurrentDirectory;
Directory.SetCurrentDirectory(jarRoot);
var pipeline = new StanfordCoreNLP(props);
Directory.SetCurrentDirectory(curDir);
foreach (string file in textFiles)
{
label3.Text = file;
// Text for processing
var text = System.IO.File.ReadAllText(file);
// Annotation
var annotation = new Annotation(text);
pipeline.annotate(annotation);
// Result - Pretty Print
string output = prettyPrint + Path.GetFileName(file);
using (var stream = new ByteArrayOutputStream())
{
pipeline.prettyPrint(annotation, new PrintWriter(stream));
System.IO.File.AppendAllText(output, stream.toString()+Environment.NewLine);
stream.close();
}
}
}
}
}
I have modified the example from official StanfordCoreNLP .Net port here.
Since I am using Windows Forms instead of Console application, this line of code is creating problem: var props = Properties();. I am not sure how to find the namespace of this method to provide a complete namespace.class.method path to disambiguate.
Another minor problem is that I want to update label text as in label2.Text = "Stanford Parser...."; but visual studio says that "An object reference is required" while I am in the same class (Forms1.cs). Your help will be greatly appreciated.
The Properties() class is java.util.Properties.
Simply remove static from the method name to access windows forms objects like text box or label.
I didn't get why it isn't working..
Error shows like, newArraylist (line 13); newSreamReader (line 14, 24)
does not exist.
Any help will be appreciated.
using System;
using System.IO;
using System.Collections;
namespace InsertLineInTextFile
{
class Program
{
static void Main(string[] args)
{
string strTextFileName = "file.txt";
int iInsertAtLineNumber = 2;
string strTextToInsert = "Amudha";
ArrayList lines = new ArrayList();
StreamReader rdr = new StreamReader(strTextFileName);
string line;
while ((line = rdr.ReadLine()) != null) lines.Add(line);
rdr.Close();
if (lines.Count > iInsertAtLineNumber) lines.Insert(iInsertAtLineNumber, strTextToInsert);
else
lines.Add(strTextToInsert);
StreamWriter wrtr = new StreamWriter(strTextFileName);
foreach (string strNewLine in lines) wrtr.WriteLine(strNewLine);
wrtr.Close();
}
}
}
First, you have to think over what you're going to achieve; reverse engeniering (alas!) says
insert strTextToInsert at iInsertAtLineNumber line of fileName file
(or add the text if the file is too short)
Then implementation:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
...
string fileName = "file.txt";
int iInsertAtLineNumber = 2;
string strTextToInsert = "Amudha";
List<String> lines = File
.ReadLines(fileName)
.ToList();
if (lines.Count > iInsertAtLineNumber)
lines.Insert(iInsertAtLineNumber, strTextToInsert);
else
lines.Add(strTextToInsert);
File.WriteAllLines(fileName, lines);
Please, do not use obsolete class ArrayList but List<T> (List<String> in the question). Often File.ReadLines and File.WriteAllLines are more readable and easier to maintain than StreamReader/StreamWriter.
How do I get the data I can write in the console to write to the array and the console.
At the moment it only displays on the console (not added functionality to add to array).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
namespace TBParser
{
class Program
{
static void Main(string[] args)
{
String[] arr = new String[100];
string[] lines = System.IO.File.ReadAllLines(#"C:\ShpereCompare3.txt");
Console.WriteLine("Contents of Text File: ");
foreach (string line in lines)
{
Console.WriteLine("\r\t" + line);
}
System.IO.File.WriteAllLines(#"C:\Test.txt",lines);
Console.WriteLine("Press any key to Exit");
Console.ReadKey();
}
}
}
if my lines of text say
hello
my
name
is
Simon
then the first 5 slots of the array should contain each line?
The line:
string[] lines = System.IO.File.ReadAllLines(#"C:\ShpereCompare3.txt");
is already creating an array, each element of which contains one line.
There is no need to populate a new array with this same information via a foreach.
If you want to copy the lines from the text file into another array, then you can do this:
String[] arr = new String[lines.Length];
Array.Copy(lines, arr, lines.Length);
found a work around. the path i was going down was too complicated. thanks for all your input
fixed code here
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
using System.IO;
using System.Text.RegularExpressions;
namespace TBParser
{
class Program
{
static void Main(string[] args)
{
string fileName = #"C:shpereCompare3.txt";
List<string> Names = new List<string>();
List<string> Value = new List<string>();
using (StreamReader fileReader = new StreamReader(fileName))
{
string fileLine;
while (!fileReader.EndOfStream)
{
fileLine = fileReader.ReadLine();
if (fileLine.StartsWith("Name"))
{
Names.Add(fileLine.Substring(21));
}
if (fileLine.StartsWith("Center"))
{
string[] fileSplit = fileLine.Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
Value.Add(fileSplit[1]);
}
}
string outputString = "";
for (int i = 0;i < Names.Count; i++)
{
outputString += Names[i] + " = " + Value[i] + "\r\n";
}
System.IO.File.WriteAllText(#"C:Test.txt", outputString);
}
}
}
}
This code times two methods of outputting a ~380Kb string:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Diagnostics;
namespace ConsoleApplication1
{
class Program
{
static string outbuff = "";
static void Main(string[] args)
{
{
Stopwatch exectime = new Stopwatch();
System.IO.StreamWriter file;
exectime.Reset(); exectime.Start();
file = new System.IO.StreamWriter("output.html");
for (int i = 0; i < 18000; i++)
{
outbuff += "444444444, 5555555555\n";
}
string fin = "\nString method took " + exectime.Elapsed.TotalSeconds + "s";
file.WriteLine(outbuff);
Console.WriteLine(fin);
file.WriteLine(fin);
file.Close();
}
{
Stopwatch exectime = new Stopwatch();
System.IO.StreamWriter file;
exectime.Reset(); exectime.Start();
file = new System.IO.StreamWriter("output2.html");
for (int i = 0; i < 18000; i++)
{
file.Write("444444444, 5555555555\n");
}
string fin = "\nDirect method took " + exectime.Elapsed.TotalSeconds + "s";
Console.WriteLine(fin);
file.WriteLine(fin);
file.Close();
}
}
}
}
String method took 2.2985349s
Direct method took 0.07191s
This is on a 3.5GHz CPU with 5Gb RAM.
I'm disappointed that simply buffering the output in a string is so costly!
In my real program, I need to deferr output until the string is assembled. Is there a faster way?
Yes, use a StringBuilder instead to assemble your string.
For an in-depth explanation for the performance boost see "Using the StringBuilder Class" - but basically because strings are immutable a new string is created when you concatenate, which is very expensive.
string EV_HOME = System.Environment.GetEnvironmentVariable("EV_HOME");
string myFilePath = EV_HOME + "\\MyFolder\\MySubFolder";
Suppose EV_HOME return C:\myprogram\leanrning\anotherfolder
How can I remove the folder anotherfolder and get myFilePath as this
C:\myprogram\leanrning\MyFolder\MySubFolder
What I know is loop the Ev_HOME value and build each one (except the last one) as a new string.
thanks.
using System;
using System.Collections.Generic;
using System.Text;
namespace ConsoleApplication12
{
class Program
{
static void Main(string[] args)
{
string EV_HOME = #"C:\myprogram\leanrning\anotherfolder\";
string parentFolder = new System.IO.DirectoryInfo(EV_HOME).Parent.FullName;
string myFilePath = parentFolder + "\\MyFolder\\MySubFolder";
Console.WriteLine(myFilePath);
}
}
}