C# adapt code to a button click event - c#

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;

Related

error in text direction when i try to extract text from arabic pdf file using itextsharp c#

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

Google maps autocomplete textbox in c#

I have a restaurant delivery WINFORM c# application where in user needs to enter the address, as to avoid human error we are trying to integrate google map's autocomplete functionality into textbox. I have googled and all I saw was for asp nothing for WINFORM. I tried one code however its namespace is missing and i am not sure which one it is
Namespace used :
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 Google.Api.Maps ;
using GoogleApi.Helpers;
Heres the code :
private void textBox1_TextChanged(object sender, EventArgs e)
{
var autoCompleteListCollection = new AutoCompleteStringCollection();
autoCompleteListCollection.AddRange(new GoogleApi.Instance.GetAddressPredictionsByInput(textBox1.Text).ToArray());
textBox1.AutoCompleteCustomSource = autoCompleteListCollection;
}
Error :
Error 1 The type or namespace name 'Instance' does not exist in the namespace 'GoogleApi' (are you missing an assembly reference?)
I think this might work. So please let me know right namespace or guide me how to achieve above requirement
Finally I got it to work, but it crashes the app, heres the code :
private void textBox1_TextChanged(object sender, EventArgs e)
{
string url = "https://maps.googleapis.com/maps/api/place/autocomplete/json?input=" + var + "&types=geocode&key=YOURAPIKEY";
string content = fileGetContents(url);
JObject o = JObject.Parse(content);
List<string> add = new List<string>();
try
{
JObject jObj = (JObject)JsonConvert.DeserializeObject(content);
int count = jObj.Count;
for (int i = 0; i < count; i++)
{
add.Add((string)o.SelectToken("predictions["+i+"].description"));
}
var collection = new AutoCompleteStringCollection();
collection.AddRange(add.ToArray());
textBox1.AutoCompleteCustomSource = collection;
textBox1.AutoCompleteMode = AutoCompleteMode.Suggest;
textBox1.AutoCompleteSource = AutoCompleteSource.CustomSource;
}
catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); }
{
}
protected string fileGetContents(string fileName)
{
string sContents = string.Empty;
string me = string.Empty;
try
{
if (fileName.ToLower().IndexOf("https:") > -1)
{
System.Net.WebClient wc = new System.Net.WebClient();
byte[] response = wc.DownloadData(fileName);
sContents = System.Text.Encoding.ASCII.GetString(response);
}
else
{
System.IO.StreamReader sr = new System.IO.StreamReader(fileName);
sContents = sr.ReadToEnd();
sr.Close();
}
}
catch { sContents = "unable to connect to server "; }
return sContents;
}
Everytime I run after few attempts it crashes.
Thanks

How to use C# to convert any file to some other arbitrary format(.rjb) & recover to original format?

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.

Streamreader problems

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.

Problem with runtime compilation in C#?

I want to download the code from http://pastehtml.com/view/awono3xoq.txt, save it to a string, then compile & run it when the button is clicked, but I can't seem to get the code below to work:
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.CodeDom.Compiler;
using Microsoft.CSharp;
using System.IO;
using System.Diagnostics;
using System.Net;
using System.Runtime.InteropServices;
namespace ASV
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
public void compile()
{
CSharpCodeProvider myCodeProvider = new CSharpCodeProvider();
ICodeCompiler myCodeCompiler = myCodeProvider.CreateCompiler();
String [] referenceAssemblies = {"System.dll"};
string myAssemblyName = "Assembly.exe";
CompilerParameters myCompilerParameters = new CompilerParameters(referenceAssemblies, myAssemblyName);
myCompilerParameters.GenerateExecutable = true;
myCompilerParameters.GenerateInMemory = true;
WebClient x = new WebClient();
Stream y = x.OpenRead("http://pastehtml.com/view/awono3xoq.txt");
StreamReader z = new StreamReader(y);
string source = z.ReadToEnd();
z.Close();
y.Close();
CompilerResults compres = myCodeCompiler.CompileAssemblyFromSource(myCompilerParameters, source);
Process.Start("Assembly.exe");
}
private void button1_Click(object sender, EventArgs e)
{
compile();
}
}
}
what am I doing wrong (other than having too many using statments :P)?
If you check CompilerResults compres it shows that there's an exception and the compilation was not successful and hence it's not writing out Assembly.exe and there is a System.IO.FileNotFound exception from Process.Start()
Try this
public void compile()
{
CSharpCodeProvider myCodeProvider = new CSharpCodeProvider();
ICodeCompiler myCodeCompiler = myCodeProvider.CreateCompiler();
string myAssemblyName = #"Assembly.exe";
CompilerParameters myCompilerParameters = new CompilerParameters
{
OutputAssembly = myAssemblyName,
GenerateExecutable = true,
GenerateInMemory = true
};
myCompilerParameters.ReferencedAssemblies.Add("System.dll");
WebClient x = new WebClient();
Stream y = x.OpenRead("http://pastehtml.com/view/awono3xoq.txt");
StreamReader z = new StreamReader(y);
string source = z.ReadToEnd();
z.Close();
y.Close();
CompilerResults compres = myCodeCompiler.CompileAssemblyFromSource(myCompilerParameters, source);
Process.Start(myAssemblyName);
}

Categories