I'm a real noob to C# trying to write a small XML replacer program based on a short code a friend of mine used in one of his apps..
I'm having trouble with this line:
StreamReader sr = new StreamReader(textBox1.Text);
I get an error: "Empty path name is not legal."
why doesn't this work?
the code is:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
namespace ReplaceMe
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
StreamReader sr = new StreamReader(textBox1.Text);
StreamWriter sw = new StreamWriter(textBox1.Text.Replace(".", "_new."));
string cur = "";
do
{
cur = sr.ReadLine();
cur = cur.Replace(textBox2.Text, textBox3.Text);
sw.WriteLine(cur);
}
while (!sr.EndOfStream);
sw.Close();
sr.Close();
MessageBox.Show("Finished, the new file is in the same directory as the old one");
}
private void textBox1_TextChanged(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
this.textBox1.Text = openFileDialog1.FileName;
}
}
}
}
Thanks in advance :)
That is because your textBox1 doesn't contain text at the moment you create StreamReader. You set textBox1 text in button1_Click, so you have to create StreamReader in that method.
You should make sure the file exists before you try to access it, it seems you deliver an empty string as a filename.
try accessing the file only when:
if (File.Exists(textBox1.Text))
{
//Your Code...
}
the value of textbox1 is null or empty. also, if you want to manipulate xml look into the objects of the System.Xml namespace. These objects are designed specifically for working with XML.
it's because you're setting an empty string in StreamReader constructor.
I recommend you do a simple validation before read file.
as this:
string fileName = textBox1.Text;
if(String.IsNullOrEmpty(fileName)) {
//textbox is empty
} else if(File.Exists(fileName)) {
//file not exists
} else {
// read it
StreamReader sr = new StreamReader(fileName);
//..
}
Note: it is not right way to manipulate xml files.
check out the XML documentation for more info.
Related
i have problem in my code
i am trying to read text from arabic rtl file using itextsharp
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 iTextSharp;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.pdf.parser;
namespace Masmo3
{
public partial class FrmMain : Form
{
string book = null;
public FrmMain()
{
InitializeComponent();
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
BtnOpen.Enabled = false;
book = null;
using(OpenFileDialog Ofd = new OpenFileDialog() {Filter= "PDF files (*.pdf)|*.pdf|txt files (*.txt)|*.txt",ValidateNames= true, Multiselect= false})
{
if (Ofd.ShowDialog() == DialogResult.OK)
{
iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(Ofd.FileName);
StringBuilder sb = new StringBuilder();
for (int i = 1; i <= reader.NumberOfPages; i++)
{
sb.Append(PdfTextExtractor.GetTextFromPage(reader, i));
book = sb.ToString();
}
reader.Close();
}
}
BtnOpen.Enabled = true;
}
}
}
this code show my text like "ﻢﯿﺣﺮﻟا ﻦﻤﺣﺮﻟا ﷲ ﻢﺴﺑ" its wrong because its rtl language the correct way "بسم الله الرحمن الرحيم"
what i can do to get correct text direction ?
"بسم الله الرحمن الرحيم"
please use ColumnText object to set the DIrection to be RTL
CT.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
Good luck bro
I am trying to adapt the following code so that the functionality is on a click event ...
Here is the code as is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
namespace ConsoleApplication1
{
class Program
{
const string IN_FILENAME = #"c:\temp\testin.csv";
const string OUT_FILENAME = #"c:\temp\testout.csv";
static void Main(string[] args)
{
StreamReader reader = new StreamReader(IN_FILENAME);
StreamWriter writer = new StreamWriter(OUT_FILENAME);
string inputLine = "";
while ((inputLine = reader.ReadLine()) != null)
{
List<string> inputArray = inputLine.Split(new char[] { ',' }).ToList();
inputArray.Add(inputArray[3]);
writer.WriteLine(string.Join(",", inputArray));
}
reader.Close();
writer.Flush();
writer.Close();
}
}
}
Then I need to add the functionality to a click even so this is where I am:
private void button1_Click(object sender, EventArgs e)
{
const string IN_FILENAME = #"c:\temp\testin.csv";
const string OUT_FILENAME = #"c:\temp\testout.csv";
StreamReader reader = new StreamReader(IN_FILENAME);
StreamWriter writer = new StreamWriter(OUT_FILENAME);
}
and I can't do anymore because it's telling me StreamReader cannot be found.
Can anyone help me adapt this code to the click event?
The StreamReader is a class define in the System.IO namespace. Using this namespace at the start of your file, you would resolve it.
using System.IO;
This is my first question in Stackoverflow
I am trying to convert some files(.txt,.mp3,.mp4,.pdf,.png,.exe etc.) in a folder to a format .rjb, created by me. And I also want to recover the original files from the .rjb files. But every files other than .txt files get corrupted. Please help me, to accomplish this. The below code is what I am using.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace rjbformat
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
if (textBox1.Text != "")
{
try
{
//string data = Convert.ToString(File.ReadAllBytes(textBox1.Text));
// string datas = File.ReadAllText(textBox1.Text);
//string dat = File.ReadAllText(textBox1.Text, Encoding.ASCII);
//var dataS = Convert.ToString(datas);
using (StreamWriter sw = new StreamWriter(textBox1.Text + ".rjb"))
{
sw.Write(textBox3.Text);
}
}
catch (Exception)
{
MessageBox.Show("Specified Input file DOESNOT EXIST!", "Error", MessageBoxButtons.OK,
MessageBoxIcon.Error);
//throw;
}
}
else
{
MessageBox.Show("Please select Input file");
}
}
private void button2_Click(object sender, EventArgs e)
{
openFileDialog1.Title = "Open Text File (Rajib)";
openFileDialog1.Filter = "Text Files(*.txt;*.cod;*.ubc)|*.txt;*.cod;*.ubc";
openFileDialog1.Filter = "All Files(*.*)|*.*";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
textBox1.Text = openFileDialog1.FileName;
textBox2.Text = openFileDialog1.FileName + ".rjb";
File.Copy(textBox1.Text, textBox2.Text,true);
FileAccess.ReadWrite.ToString(textBox1.Text);
var lines = File.ReadAllLines(textBox1.Text);
/* foreach (string line in lines)
{
textBox3.Text += line+"\r\n";
}*/
File.AppendAllLines(textBox2.Text, lines);
// FileStream fs = new FileStream(textBox1.Text, FileMode.Open);
// int hexIn;
// String hex = "";
// for (int i = 0; i<50/*(hexIn = fs.ReadByte()) != -1*/; i++)
// {
// hex = string.Format("{0:X2}", fs.ReadByte());
// // int bina = fs.ReadByte();
// textBox3.Text += hex;
//}
}
}
}
}
If all you are doing is storing one or more files into your .rjb format and want to get them back intact, this sounds a lot like creating archive files. In that case, you may want to consider just using a standard zip file and customize the extension.
Here's an example using the ZipArchive class:
using System.IO.Compression;
namespace CustomZip
{
class Program
{
static void Main(string[] args)
{
string startPath = #"c:\example\start";
string zipPath = #"c:\example\result.rjb";
string extractPath = #"c:\example\extract";
ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);
}
}
}
You will need to add a reference to System.IO.Compression.FileSystem to your project.
I have created 2 text boxes that take the name and email address, stores it in a "text" file and display the contents in a list box. I have everything done but when it displays in the list box this is the output that I get.
"System.Windows.Forms.TextBox, Text: tony"
"System.Windows.Forms.TextBox, Text: tony#tony.com"
Can anyone tell me why it is doing that please? I'm still new to c# and I know this is a minor thing I just do not know where to look
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;
namespace _iLab_Week7
{
public partial class Form1 : Form
{
private StreamReader inFile; //streamreader for input
private StreamWriter outFile; //streamwriter for output
const string filename = "contacts.txt";
public Form1()
{
InitializeComponent();
}
private void btnAddContact_Click(object sender, EventArgs e)
{
//Disable the "add contact" and "email"
btnAddContact.Enabled=false;
txtBoxEmail.Enabled=false;
//check for and create contacts.txt file
if(!File.Exists(filename))
File.Create(filename);
if(File.Exists(filename))
{
try
{
//create the file stream
outFile = new StreamWriter(filename, true);
//get the item from the name and email text box
//write it to the file
outFile.WriteLine(txtBoxName);
outFile.WriteLine(txtBoxEmail + "\n");
//close the file
outFile.Close();
//clear the textbox
txtBoxName.Text="";
txtBoxEmail.Text="";
//the cursor in the text box
txtBoxName.Focus();
txtBoxEmail.Focus();
}
catch (DirectoryNotFoundException exc)
{
lstBoxContact.Items.Add(exc.Message);
}
catch (System.IO.IOException exc)
{
lstBoxContact.Items.Add(exc.Message);
}
string listItem;
this.lstBoxContact.Items.Clear();
btnAddContact.Enabled = false;
try
{
//open file for reading
inFile=new StreamReader(filename);
//read from file and add to list box
while ((listItem=inFile.ReadLine()) !=null)
{
this.lstBoxContact.Items.Add(listItem);
}
//Close the file
inFile.Close();
}
catch (System.IO.IOException exc)
{
this.lstBoxContact.Items.Add(exc);
}
}
else
{
this.lstBoxContact.Items.Add("File Unabailable");
}
}
private void lstBoxContact_SelectedIndexChanged(object sender, EventArgs e)
{
//enable button
btnAddContact.Enabled = true;
txtBoxName.Enabled = true;
txtBoxEmail.Enabled = true;
}
private void Form1_FormClosing(object sender, FormClosedEventArgs e)
{
//make sure files are closed
try
{
inFile.Close();
outFile.Close();
}
catch { }
}
}
Replace
outFile.WriteLine(txtBoxName);
outFile.WriteLine(txtBoxEmail + "\n");
with
outFile.WriteLine(txtBoxName.Text);
outFile.WriteLine(txtBoxEmail.Text + "\n");
and try...
ADDED : When you say txtBoxName, you are referring to the txtBoxName object as a whole, which contains many properties - like Text, ForeColor, Font etc.... To get only the value or content, you need to specify the property which gives you that - which is the Text property
More about TextBox
outFile.WriteLine(txtBoxName);
is equivalent to
outFile.WriteLine(txtBoxName.ToString());
For most classes, the ToString() method is the same as Object.ToString(). This method just displays the name of the type of the instance you're trying to display. So you might have only seen
System.Windows.Forms.TextBox
However, the TextBox class helpfully overrides this method and displays both the type name and the value of the Text property.
But as Saagar Elias Jacky said. This is not what you actually intended to do, so just display txtBoxName.Text as he suggested.
I'll try my best to explain my situation.
I'm developing a software using C#, which allows multiple users to edit the same file under a common directory at the same time and see the changes others make too.
So I used FileSystemWatcher to monitor the changes in the file (to update others' changes) and textchanged of the textbox (to save changes to the file so others' screen would be updated too).
It's working if I input characters (both events are fired once)
It's not working if I try to delete characters in any form (backspace, delete, etc) It won't delete any character and the cursor always gets reset to position 0. I used box.SelectionStart to move the cursor and it's working when I input characters.
I put a counter kinda thing to check and I found that when I tried to delete characters, both events are fired twice.
I tried to search but I got mixed answers...
Thanks in advance
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;`enter code here`
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Windows.Forms;
using System.IO;
using System.Windows.Threading;
namespace SharedFileEditor
{
public partial class EditorView : Window
{
private EditorModel model;
private FileSystemWatcher watcher;
private string path;
private int count = 0;
private int count2 = 0;
public EditorView()
{
InitializeComponent();
model = new EditorModel();
this.DataContext = model;
}
private void OpenClicked(object sender, RoutedEventArgs e)
{
using (OpenFileDialog dialog = new OpenFileDialog())
{
dialog.Filter = "Text files (*.txt)|*.txt";
if (dialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
watcher = new FileSystemWatcher(System.IO.Path.GetDirectoryName(dialog.FileName), "*.txt");
Console.WriteLine(System.IO.Path.GetDirectoryName(dialog.FileName));
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEve`enter code here`nts = true;
path = dialog.FileName;
HandleOpen(dialog.FileName);
}
}
}
internal void HandleOpen(string path)
{
FileStream f = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
StreamReader reader = new StreamReader(f);
model.Content = reader.ReadToEnd();
reader.Close();
}
private void OnChanged(object source, FileSystemEventArgs e)
{
if (this.Box.Dispatcher.CheckAccess())
{
try
{
FileStream f = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
StreamReader reader = new StreamReader(f);
model.Content = reader.ReadToEnd();
this.Box.CaretIndex = model.Cursor;
reader.Close();
Console.WriteLine("read:" + count2++);
}
catch (IOException x)
{
Console.WriteLine(x.Message);
}
}
else
{
this.Box.Dispatcher.Invoke(
new updateContent(OnChanged), source, e);
}
}
private void ContentChanged(object sender, TextChangedEventArgs e)
{
FileStream f = File.Open(path, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.ReadWrite);
StreamWriter writer = new StreamWriter(f);
writer.Write(this.Box.Text);
model.Cursor = this.Box.SelectionStart;
model.Content = this.Box.Text;
writer.Close();
Console.WriteLine("write:"+count++);
}
public delegate void updateContent(object source, FileSystemEventArgs e);
}
}
I figured it out... it has something to do with how my application works. Solved by setting the EnableRaisingEvents flag to false and back to true later.
I think the actual answer to your question is contained in this post:
FileSystemWatcher Changed event is raised twice
To summarize, this is a bug in the FileSystemWatcher class. The save process often occurs in batches. Your FileSystemWatcher class picks them all up.