Edit .Bat File In C# - c#

Well, first of all my code :
protected void Button2_Click1(object sender, EventArgs e)
{
string batname = edit.SelectedValue;
StreamWriter sw = new StreamWriter("D:\\MPSite-Serv\\bats\\" + batname);
string theedit = batedit.Text;
sw.WriteLine(theedit);
sw.Flush();
}
When I click on button2 and try to write all of the text into the bat file, I get this result the bat file contains:
System.Web.UI.WebControls.TextBox
Why is that?
I am using all of the following statements, if it helps:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using System.Diagnostics;

You are getting the type name of the textbox, which leads me to believe that your code rather looks something like:
sw.WriteLine(batedit);
I.e. you are sending the textbox object itself to be written to the file instead of the contents of its Text property. This will implicitly call the ToString method, which by default returns the type name of the object.
Also, you are not closing the StreamWriter properly, which might cause problems when you want to use it. You should call the Close method, and you don't have to call Flush before closing the StreamWriter. Alternatively you can put the StreamWriter in a using block, which would dispose it automatically, which will close it.

http://msdn.microsoft.com/en-us/library/system.io.streamwriter.aspx#Y2863
The problem is simple: sw.writeline expects a string. You are sending it a text object which gets turned into the aformentioned .ToString(); which means your line gets translated, loosely, into
sw.WriteLine(theedit.ToString());
if you look at the documentation for WebControls.TextBox... scroll down the list to the Method ToString()
http://msdn.microsoft.com/en-us/library/system.web.ui.webcontrols.textbox.aspx
What you need to do... is give it one string at a time (although I assume you could just give it the raw string from the textbox):
using System.IO;
namespace String_Writer
{
class Program
{
static void Main(string[] args)
{
string batname = "test.txt";
string theedit = "Testing one two three four\n\nfive six seven eight.";
using(StreamWriter sw = File.CreateText("C:\\Users\\Kriis\\Desktop\\" + batname))
{
using (StringReader reader = new StringReader(theedit))
{
string line = string.Empty;
do
{
line = reader.ReadLine();
if (line != null)
{
sw.WriteLine(line);
}
} while (line != null);
}
}
}
}
}

Related

How to create file using streamwriter in c# in which the content is inputed by users using cmd

I created a console application which accepts arguments. After building the program i will run it through cmd in which the user will input like this "filemgr.exe create [filename] [contents]" . My code is below. I want to enter "my text here" content, but when i check the output, only the FIRST word is displayed which is the "my", how to include the rest of the strings?(which is the text here)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace filemgr
{
class Program
{
static void Main(string[] args)
{
if (args[0]=="create")
{
using (StreamWriter file = new StreamWriter(args[1]))
{
file.Write(args[2]);
}
}
}
}
}
You need to recombine the args array into a string (although this method will likely lose quotes):
file.Write(string.Join(" ", args.Skip(2)));
Alternatively you can quote the string in the commandline:
program.exe create test.txt "hello this is a message"
Also, if you want to append to the file through sequential calls you need to open the stream like so:
using (StreamWriter file = new StreamWriter(args[1], true))
This signifies that you want append mode, and not create/replace.
Pass content args in double quotes
filemgr.exe create [filename] "[contents]"
filemgr.exe create C:\test.txt "my file content"
I would suggest to use quotes even in file path as well. When you use args, its always a chance to make mistake while accessing arguments.

Using StreamReader to read lines as defined by other lines [duplicate]

This question already has an answer here:
No StreamReader constructor accepting a string
(1 answer)
Closed 5 years ago.
I have a problem that requires me to calculate synthetic student marks from a text file. It gives me the weights of the marks in the first row, the number of students to evaluate in the next row, and then the next rows are the students' marks. This pattern repeats through the file without major separation.
For clarity, the text file and problem are here:
I've tried making a new object with streamreader using the following code:
using (StreamReader sr = new StreamReader("DATA10.txt")) {
blahblahblah;
}
DATA10.txt is in the same folder as the program.
But I get "Cannot convert from 'string' to 'System.IO.Stream'", even though in the examples on MSDN and everywhere else use that exact code just fine. What am I doing wrong?
Eventually what I'll be doing is taking the value from the second line and using streamreader to read that amount of lines. Then repeating the whole process on the next set of data.
I really don't think it's a duplicate of that question, and the answers here are expressed in an easier to understand way.
StreamReader is suppose to take in a Stream as its parameter can also take in a Stream as a parameter and you will also have to specify the FileMode.
Instead, try something like this:
public static void Main()
{
string path = #"c:\PathToFile\DATA10.txt";
try
{
using (FileStream fs = new FileStream(path, FileMode.Open))
{
using (StreamReader sr = new StreamReader(fs))
{
//blahblah
}
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
MSDN Reference
You must also set the "Copy to output directory" property of "DATA10.txt" in Solution Explorer to "Copy Always"
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _07___ReadTextFileWhile
{
class Program
{
static void Main(string[] args)
{
StreamReader myReader = new StreamReader("DATA10.txt");
string line = "";
while (line != null)
{
line = myReader.ReadLine();
if (line != null)
Console.WriteLine(line);
}
myReader.Close();
Console.ReadKey();
}
}
}

Why doesn't FileStream as an argument to Streamwriter write to text file?

In the code included below, I am able to write the contents of the string 'fullname' to a text file in the specified directory when using the following statement:
System.IO.File.WriteAllText(path, fullname);
However, if I write the string path to a FileStream object (withe arguments specified), and then pass that FileStream object as an argument to the StreamWriter object, the file is created, but no contents are written.
First attempt: Comment out System.IO.File.WriteAllText(path, fullname); and use the three lines above it. This creates the file but no contents are written into the file.
Second attempt: Un-comment the System.IO.File.WriteAllText(path, fullname); statement and comment the three lines above it. This executes as desired.
Here is the full block of code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace FileInputOutput
{
class Program
{
static void Main(string[] args)
{
// Use the Split() method of the String Class
string fullname = " Robert Gordon Orr ";
fullname = fullname.Trim();
string[] splitNameArray = fullname.Split(' ');
Console.WriteLine("First Name is: {0}", splitNameArray[0]);
Console.WriteLine("Middle Name is: {0}", splitNameArray[1]);
Console.WriteLine("Last Name is: {0}", splitNameArray[2]);
Console.WriteLine("Full name is: {0}", fullname);
string path = #"C:\Programming\C#\C# Practice Folder\Console Applications\FileInputOutput\textfile.txt";
FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite);
StreamWriter toFile = new StreamWriter(fs);
toFile.Write(fullname);
//System.IO.File.WriteAllText(path, fullname);`enter code here`
Console.ReadLine();
}
}
}
As others have said: streams must be flushed in .NET in order for them to write to disk. This can be done manually, however I would simply change your code to have using statements on your streams:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace FileInputOutput
{
class Program
{
static void Main(string[] args)
{
// Use the Split() method of the String Class
string fullname = " Robert Gordon Orr ";
fullname = fullname.Trim();
string[] splitNameArray = fullname.Split(' ');
Console.WriteLine("First Name is: {0}", splitNameArray[0]);
Console.WriteLine("Middle Name is: {0}", splitNameArray[1]);
Console.WriteLine("Last Name is: {0}", splitNameArray[2]);
Console.WriteLine("Full name is: {0}", fullname);
string path = #"C:\textfile.txt";
using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite))
{
using (StreamWriter toFile = new StreamWriter(fs))
{
toFile.Write(fullname);
}
}
//System.IO.File.WriteAllText(path, fullname);`enter code here`
Console.ReadLine();
}
}
}
Calling Dispose() on a stream (as using implicitly does), causes the stream to be flushed and closed at the end of the using block.
I think you are just forgetting to flush your file stream:
fs.Flush();
This is needed because according to msdn, this is what makes the FileStream to actually write the buffer to the file.
Flush: Clears buffers for this stream and causes any buffered data to be written to the file. (Overrides Stream.Flush().)
Regards.
From MSDN on StreamWriter
You must call Close to ensure that all data is correctly written out to the underlying stream.
So the problem here is mainly that, since you don't actually close the StreamWriter, the data gets backed up but doesn't push to the file, even though the FileStream immediately created the file in its constructor. Never ever forget to close your stream, as failing to do so could lead to major problems down the line.

c# - use a file to open soft and read from it

I want to launch my soft directly by open a file with a specific extension (here no problem) but I was wondering how read directly the content of this file ?
I checked on internet but nothing useful came out.
Thanks
Try to use the File class, in particular the File.ReadAllText Method
Sample MSDN usage
using System;
using System.IO;
using System.Text;
class Test
{
public static void Main()
{
string path = #"c:\temp\MyTest.txt";
// This text is added only once to the file.
if (!File.Exists(path))
{
// Create a file to write to.
string createText = "Hello and Welcome" + Environment.NewLine;
File.WriteAllText(path, createText);
}
// This text is always added, making the file longer over time
// if it is not deleted.
string appendText = "This is extra text" + Environment.NewLine;
File.AppendAllText(path, appendText);
// Open the file to read from.
string readText = File.ReadAllText(path);
Console.WriteLine(readText);
}
}
In order to read the file name from the command line (invoked on double click)
using System;
using System.IO;
using System.Text;
class Test
{
public static void Main(string[] args)
{
Console.Writeline("I bet your filename is: {0}", args[0]);
}
}
See also this very nice example.
File.ReadAllLines is waht your looking for, you should provide an Serilizer to get your spezific data from that file.
But what do you want do read from that file? if it is an executable i think you don't want to read that file or?

Using StreamWriter to append text

The following program should open/create a file and write the current date to it's end every time.
using System;
using System.IO;
using System.Text;
namespace roughDraft
{
class Program
{
public static void Main()
{
StreamWriter oFile = File.AppendText("baza.txt");
string output = "Current date and time: " + DateTime.Now.ToString("yyyy.MM.dd hh:mm:ss");
oFile.WriteLine(output);
Console.WriteLine(output);
Console.ReadKey();
}
}
}
I don't know why does it only create an empty file.
You should always put StreamWriter objects in a using statement so they get closed properly.
using (StreamWriter oFile = File.AppendText("baza.txt"))
{
string output = "Current date and time: "
+ DateTime.Now.ToString("yyyy.MM.dd hh:mm:ss");
oFile.WriteLine(output);
}
Alternatively, you can manually call the Close method on the StreamWriter, but the using statement, to me, is much easier and less error-prone.
Its creating empty file because you are writing in it but not closing the StreamWriter
like this oFile.Close();

Categories

Resources