I have small class for text files:
using System.IO;
namespace My_Application
{
public static class FileIO
{
public static void WriteText(string filename, string text)
{
StreamWriter file = new StreamWriter(filename);
file.Write(text);
file.Close();
}
public static string ReadText(string filename)
{
StreamReader file = new StreamReader(filename);
string text = file.ReadToEnd();
file.Close();
return text;
}
}
}
My main file:
using System;
using System.Windows.Forms;
namespace My_Application
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private string readTestFile()
{
// error is here:
return FileIO.ReadFile("test.txt");
}
}
}
Im getting error:
My_Application.FileIO' does not contain a definition for 'ReadFile'
This is weird, because I was using that class in another application and it worked.
Only difference I catched, is that other application had one word name without "_".
Edit/added later:
OK. My problem was bad method name. However this is still weird, because IntelliSense suggests nothing when I write FileIO. (i also tried to press ctrl-space).
Additional question: Why IntelliSense does not see these methods?
Your method is called ReadText but you're trying to call ReadFile.
Declaration:
public static string ReadText(string filename)
and usage:
return FileIO.ReadFile("test.txt");
It shouldn't be
return FileIO.ReadFile("test.txt");
It should be
return FileIO.ReadText("test.txt");
Related
So, I have a public partial class called Condensed. Each instance of condensed is supposed to have its own file path which it will load data from, which I tried to create by having a private static string called Path I then create 6 instances of Condensed, but I found out that when I change one of the values of Path that all of the instances of Condensed set their value of Path to the most recent one
public partial class Condensed : UserControl
{
private static string Path;
public Sender Export()
{
//this uses Path to Load data then return it to the main class
}
public void Load(string path)
{
Path = path
}
}
And then inside my main class I do as follows:
public class Main
{
public void Load_Condensed()
{
condensed1.Load(Paths[0]);
condensed2.Load(Paths[1]);
condensed3.Load(Paths[2]);
condensed4.Load(Paths[3]);
condensed5.Load(Paths[4]);
condensed6.Load(Paths[5]);
}
private void exportToolStripMenuItem_Click(object sender, EventArgs e)
{
List<Condensed> Pokemon = new List<Condensed>
{
condensed1.Export(),
condensed2.Export(),
condensed3.Export(),
condensed4.Export(), //Loads all of the data from calling Export()
condensed5.Export(),
condensed6.Export()
};
Export(Condensed); //Sends the data
}
}
Paths[] is just an array of file paths stored as a public array of strings.
Basically I want each instance of Condensed to have its own unique string Path which can be used inside of the instance it is created for, how do i do this?
Your Path-field is static, which means it gets shared between all instances.
Modify it to an instance field to have it different for each instance:
public partial class Condensed : UserControl
{
private string Path; // No static here
public Sender Export()
{
this uses Path to Load data then return it to the main class
}
public void Load(string path)
{
Path = path
}
}
The fact that it is a partial class, doesn't really have anything to do with it. Partial classes just mean that you can define the class in separate files (in this case because it's a usercontrol that needs to set up some code for the UI)
The static is causing your problem because it uses shared memory between all instances of the Condensed class, just remove the static keyword from your property definition.
using System;
namespace ConsoleApp
{
class Program
{
static void Main()
{
var condensed1 = new Condensed() { FilePath = "/filepath1/" };
var condensed2 = new Condensed() { FilePath = "/filepath2/blah/" };
var condensed3 = new Condensed() { FilePath = "/filepath3/blah/blah/" };
Console.WriteLine(condensed1.FilePath);
Console.WriteLine(condensed2.FilePath);
Console.WriteLine(condensed3.FilePath);
Console.ReadKey();
}
}
public partial class Condensed
{
public string FilePath { get; set; }
}
}
Add new constructor like
public Condensed(string path)
{
Path = path
}
And when you create an instance of Condensed class, call it like
Condensed c1 = new Condensed("C/Desktop/blabla");
c1.Export();
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
I'm creating a DLL for a application that I make.
But I got a error when I added the DLL as refference to the console Application but do not know what it means this is the error:
An unhandled exception of type 'System.TypeInitializationException' occurred in ConsoleApplication1.exe
And this is my dll class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace Steap
{
public class SteapAPI
{
public static String URL
{
get;
set;
}
public static XmlReader r = XmlReader.Create(URL + "?xml=1&l=english");
public int getSteamID64()
{
int ID = 0;
r.ReadToFollowing("steamID64");
ID = r.ReadContentAsInt();
return ID;
}
public string getSteamID()
{
string ID = String.Empty;
r.ReadToFollowing("steamID");
ID = r.ReadContentAsString();
return ID;
}
public int getVac()
{
int Vac = 0;
r.ReadToFollowing("vacBanned");
Vac = r.ReadContentAsInt();
return Vac;
}
public bool hasVac()
{
if (getVac() == 0)
{
return false;
}
else
{
return true;
}
}
// =================== [ Aliases
public string getName()
{
return getSteamID();
}
}
}
Console application code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Steap;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
SteapAPI sapi = new SteapAPI(); // TypeInitializationException was unhandled error here
SteapAPI.URL = "http://steamcommunity.com/id/bluesephire";
Console.ReadKey();
}
}
}
What is wrong or what is missing
You have exception during initialization of static field of your class that leads to failure to load the class and hence the TypeInitializationException exception.
Particular line:
public static XmlReader r = XmlReader.Create(URL + "?xml=1&l=english");
URL is not initialized at the time method called (and even if it would have static value like URL=#"c:\file.txt" there is no guarantee that one field will be initialized first.
Note from that point any access to the SteapAPI class will throw the TypeInitializationException even if it is not touching fields directly involved into original exception.
In this case you shouldn't be using static fields. Static fields will cause huge problems if you ever create two SteapAPI objects, in that when you set one URL, it will overwrite the other one, and you'll never be able to re-initialize the XmlReader.
Here is how the API class should be rewritten to be a full instance class:
namespace Steap
{
public class SteapAPI
{
public String URL
{
get;
set;
}
public XmlReader r;
public SteapAPI(string url)
{
URL = url;
//NOTE: This is wrong! You can't create an XmlReader with a URL
//and expect it to fetch a web resource.
r = XmlReader.Create(URL + "?xml=1&l=english");
}
public int getSteamID64()
{
int ID = 0;
r.ReadToFollowing("steamID64");
ID = r.ReadContentAsInt();
return ID;
}
public string getSteamID()
{
string ID = String.Empty;
r.ReadToFollowing("steamID");
ID = r.ReadContentAsString();
return ID;
}
public int getVac()
{
int Vac = 0;
r.ReadToFollowing("vacBanned");
Vac = r.ReadContentAsInt();
return Vac;
}
public bool hasVac()
{
if (getVac() == 0)
{
return false;
}
else
{
return true;
}
}
// =================== [ Aliases
public string getName()
{
return getSteamID();
}
}
And then to use it in your program:
class Program
{
static void Main(string[] args)
{
SteapAPI sapi = new SteapAPI("http://steamcommunity.com/id/bluesephire");
Console.ReadKey();
}
}
Its a minor change but the benefits are huge, you should learn more about using constructors and the drawbacks of static fields/properties as it applies to multiple instances. Just remember, a static field/property of a non-static class is shared between all "instances" of the class, so setting one will set all "instances" of that class to the new value. This is especially important when doing I/O operations and file/resource reading/writing.
How to use a same StreamWriter across various methods in a class. For eg.
public class XMLWriter
{
public export(string filename)
{
StreamWriter sw = new StreamWriter(filename)
sw.write("Line1")
}
public footer()
{
// Note: I am not declaring streamwriter here since i want to use the same sw as in export method
sw.write("Line x N")
}
}
How can I use the same sw across many methods. Also this class will be instantiated from another class and the "public" methods will be called from there.
Any help will be highly appreciated.
Declare sw as a global variable, and only close and dispose it when you dispose your XMLWriter object (or when you know you won't write more into your file) with calling the DisposeWriter() method below from the class where you created that object:
public class MyClass
{
private void DoSomeStuff()
{
XMLWriter xmlwr = new XMLWriter();
xmlwr.export(#"C:\YourFile.txt");
xmlwr.footer();
xmlwr.DisposeWriter();
wmlwr = null;
}
}
public class XMLWriter
{
private StreamWriter sw;
public XMLWriter()
{
//this is the constructor, what you call with "new XMLWriter()"
}
public void export(string filename)
{
sw = new StreamWriter(filename)
sw.write("Line1")
}
public void footer()
{
sw.write("Line x N")
}
public void DisposeWriter()
{
sw.Close();
sw.Dispose();
}
}
I would just declare thee steamwriter above the methods (global variable) and do the work inside the methods
Pass it as parameter or use a private field - depends on you requirements.
using System;
using System.IO;
using System.Text;
public class XMLWriter
{
//Objs
private StreamWriter sw;
private StringBuilder sb;
//static items
private string strHeader;
private string strFooter;
public XMLWriter()
{
//this is the constructor, what you call with "new XMLWriter()"
}
public void export(string filename)
{
sb = new StringBuilder();
sw = new StreamWriter(filename);
sw.Write(strHeader + sb.ToString() + strFooter);
sw.Close();
sw.Dispose();
}
public string Footer
{
set
{
strFooter = value;
}
}
public string Header
{
set
{
strHeader = value;
}
}
public string LinesAdd
{
set
{
sb.Append(value);
}
}
}
I am new to c# and just switched from c++ to c#.
I was doing something like this in c++:
Class A
{
public : A(char *argv);//declaration of constructor
}
then in main i was doing like this:
int main(int argc, char **argv)
{
A Obj(argv[1]);
}
then definition of constructor i do like this :
A::A(char * argv)
{
//Here i use this command line argument argv which contains a file.
}
I tried to write equivalent code in c# which is as follows:
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace shekhar_final
{
class Huffman
{
public int data_size,length,i,is_there, total_nodes;
string code;
Huffman(char *args);
}
public Huffman(char *args) //called from MyClass Line:16
{
using (var stream = new BinaryReader(System.IO.File.OpenRead(args[0]))) //Line : 18
{
while (stream.BaseStream.Position < stream.BaseStream.Length)
{
byte processingValue = stream.ReadByte();
}
}
}
public class MyClass
{
public static void Main(string[] args)
{
Huffman ObjSym =new Huffman(args);//object creation
}
}
}// Line:34
The couple of errors i got are ://I have indicated the line corresponding to the errors in my code
shekhar_c#.cs(16,25): error CS1525: Unexpected symbol `Huffman', expecting `class', `delegate', `enum', `interface', `partial', or `struct'
shekhar_c#.cs(18,33): error CS1530: Keyword `new' is not allowed on namespace elements
shekhar_c#.cs(18,36): error CS1525: Unexpected symbol `BinaryReader', expecting `class', `delegate', `enum', `interface', `partial', or `struct'
shekhar_c#.cs(18,79): warning CS0658: `value' is invalid attribute target. All attributes in this attribute section will be ignored
shekhar_c#.cs(34,1): error CS8025: Parsing error
Compilation failed: 4 error(s), 1 warnings
Could you please help me in writing c# equivalent of this c++ (removing these errors). Extra guidance are also welcome because i am beginner to c#.
Unlike C++ where you have a choice of combining the declaration and the definition of a member function in the header, or placing the declaration in the header and the implementation in the cpp file, in C# there is no such choice: if a function has a body (i.e. it is not abstract), the body needs to be part of the declaration:
class Huffman
{
public int data_size,length,i,is_there, total_nodes;
string code;
Huffman(string args) {
using (var stream = new BinaryReader(System.IO.File.OpenRead(args)))
{
while (stream.BaseStream.Position < stream.BaseStream.Length)
{
byte processingValue = stream.ReadByte();
}
}
}
}
In C#, declarations and implementations go together:
namespace shekhar_final
{
class Huffman
{
public int DataSize {get; set;}
public int Length {get; set;}
public int I {get;set;}
public int IsThere {get;set;}
public int TotalNodes {get;set;}
private string code;
public Huffman(string[] args) //called from MyClass Line:16
{
using (var stream = new BinaryReader(System.IO.File.OpenRead(args[0]))) //Line : 18
{
while (stream.BaseStream.Position < stream.BaseStream.Length)
{
byte processingValue = stream.ReadByte();
}
}
}
}
public class MyClass
{
public static void Main(string[] args)
{
Huffman objSym = new Huffman(args);//object creation
}
}
}// Line:34
You don't define methods ahead of time in C# - they're defined within the class itself. Try this instead:
class Huffman
{
public int data_size,length,i,is_there, total_nodes;
string code;
public Huffman(char *args) //called from MyClass Line:16
{
using (var stream = new BinaryReader(System.IO.File.OpenRead(args[0]))) //Line : 18
{
while (stream.BaseStream.Position < stream.BaseStream.Length)
{
byte processingValue = stream.ReadByte();
}
}
}
}
public class MyClass
{
public static void Main(string[] args)
{
Huffman ObjSym =new Huffman(args); //Here is the error
}
}
The main phlosophy between C# and C++ are different. In C++ you have a header file and an implementation file. In C#, everthing needs to be within a class. So, you declare the constructor to the class and put the implementation within it.
class funny {
public funny() {
... add your constructor stuff here
}
... other stuff ...
}
C# requires constructors to be defined within the class:
using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace shekhar_final
{
public class Huffman{
public int data_size,length,i,is_there, total_nodes;
string code;
public Huffman(string[] args) //called from MyClass Line:16
{
using (var stream = new BinaryReader(System.IO.File.OpenRead(args[0]))) //Line : 18
{
while (stream.BaseStream.Position < stream.BaseStream.Length)
{
byte processingValue = stream.ReadByte();
}
}
}
}
public class MyClass
{
public static void Main(string[] args)
{
Huffman ObjSym =new Huffman(args);//object creation
}
}
}// Line:34
In c# you do not separate declaration and definition. There is no such concept as declaration in c# since all the types exist together in an assembly. If you wish to use multiple files in c3 for classes you can use the concept of partial classes.
I have a method that I want to use in almost all the classes within a same c# project.
public void Log(String line)
{
var file = System.IO.Path.GetPathRoot(Environment.SystemDirectory)+ "Logs.txt";
StreamWriter logfile = new StreamWriter(file, true);
// Write to the file:
logfile.WriteLine(DateTime.Now);
logfile.WriteLine(line);
logfile.WriteLine();
// Close the stream:
logfile.Close();
}
What is the approach to reuse this method in other classes of the project?
If you want to use it in all classes, then make it static.
You could have a static LogHelper class to better organise it, like:
public static class LogHelper
{
public static void Log(String line)
{
var file = System.IO.Path.GetPathRoot(Environment.SystemDirectory)+ "Logs.txt";
StreamWriter logfile = new StreamWriter(file, true);
// Write to the file:
logfile.WriteLine(DateTime.Now);
logfile.WriteLine(line);
logfile.WriteLine();
// Close the stream:
logfile.Close();
}
}
Then call it by doing LogHelper.Log(line)
You can make a static class and put this function in that class.
public static MyStaticClass
{
public static void Log(String line)
{
// your code
}
}
Now you can call it elsewhere. (No need to instantiate because it's a static class)
MyStaticClass.Log("somestring");
You can use Extrension method in statis class
Sample on string extension
public static class MyExtensions
{
public static int YourMethod(this String str)
{
}
}
link : http://msdn.microsoft.com/fr-fr/library/vstudio/bb383977.aspx