I can't seem to get access to the file I'm working with in the program I'm writing. I'm not sure how exactly to work this since I want my program to open a file of your choice, which it does, then I want it to be able to take in info into an arrary, which it does, then from there, write that information from the array to the file you opened up. When I try some code to start working on it it tells me, "The process cannot access the file 'file' because it is being used by another process." Here is what I have so far. Please let me know. Thank you. The problematic areas is the Save_Click section of the code where I wrote "This is a test" Thanks.
public partial class ListingSearch : Form
{
string line;
DialogResult result;
string fileName;
int i = 0;
string[] first = new string[100];
string[] last = new string [100];
string[] phone = new string [100];
string[] grade = new string [100];
public ListingSearch()
{
InitializeComponent();
MessageBox.Show("Please be sure to open a file before beginning");
}
private void OpenFile_Click(object sender, EventArgs e)
{
using (OpenFileDialog filechooser = new OpenFileDialog())
{
result = filechooser.ShowDialog();
fileName = filechooser.FileName;
System.IO.StreamReader file =
new System.IO.StreamReader(fileName);
while ((line = file.ReadLine()) != null)
{
string[] words = File.ReadAllText(fileName).Split(new string[] { "\n", "\r\n", ":" }, StringSplitOptions.RemoveEmptyEntries);
//firstName.Text = words[4];
//lastName.Text = words[5];
//telephone.Text = words[6];
//GPA.Text = words[7];
}
Read.Enabled = true;
}
}
private void Save_Click(object sender, EventArgs e)
{
File.AppendAllText(fileName, "This is a test");
}
private void Read_Click(object sender, EventArgs e)
{
MessageBox.Show(fileName);
MessageBox.Show(File.ReadAllText(fileName));
}
private void info_Click(object sender, EventArgs e)
{
first[i] = firstName.Text;
firstName.Text = " ";
last[i] = lastName.Text;
lastName.Text = " ";
phone[i] = telephone.Text;
telephone.Text = " ";
grade[i] = GPA.Text;
GPA.Text = " ";
i++;
}
private void displayinfo_Click(object sender, EventArgs e)
{
if (i == 0)
MessageBox.Show("Nothing to display!");
else
for (int j = 0; j < i; j++)
{
MessageBox.Show(first[j] + " " + last[j] + "\r" + phone[j] + "\r" + grade[j]);
}
}
You get error here
File.ReadAllText(fileName)
because you open same file before it here
System.IO.StreamReader file = new System.IO.StreamReader(fileName);
You need to close the file after you are finished reading it. Also, not sure why you are opening the file at all, since you subsequently use File.ReadAllText which will handle opening and closing the file all on its own.
Seems like your OpenFile_click event should just look like this:
using (OpenFileDialog filechooser = new OpenFileDialog())
{
result = filechooser.ShowDialog();
fileName = filechooser.FileName;
string[] words = File.ReadAllText(fileName).Split(new string[] { "\n", "\r\n", ":" }, StringSplitOptions.RemoveEmptyEntries);
Read.Enabled = true;
}
You haven't closed your StreamReader. C# will lock the file until you do. Or you could use a StreamWriter after you closed your StreamReader
Related
Hello I have created a program that contains a btnCopy associated with a copyfiledialog, I would like to know why when I press the btnCopy it copies me several files at the same time, I would like that it copies the files one after the other, can will you help me?
private void btnCopy_Click(object sender,EventArgs e)
{
string sourceDir = #"C:\Users\PORTABLEHP\Documents";
string destDir = #"C:\Users\PORTABLEHP\Documents\xgen";
try
{
string [] txtList = Directory.GetFiles(sourceDir,"*.txt");
foreach (string f in txtList)
{
try
{
string fName = f.Substring(sourceDir.Length + 1);
string [] files = new string[sourceDir.Length];
progressBar1.Value = 1;
progressBar1.Minimum = 0;
progressBar1.Maximum = files.Length;
for(int i = 1;i < files.Length; i++)
{
progressBar1.PerformStep();
File.Copy(Path.Combine(sourceDir,fName),
Path.Combine(destDir,fName), true);
}
}
catch(IOException copyerror)
{
MessageBox.Show(copyerror.Message)
}
,
Try this:
using System;
using System.IO;
using System.Windows.Forms;
using Microsoft.VisualBasic.FileIO;
public partial class Form1 : Form
{
// other code
private void button1_Click(object sender, EventArgs e)
{
string sourceDir = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string destDir = Path.Combine(sourceDir, "xgen");
string[] txtList =
Directory.GetFiles(sourceDir, "*.txt");
progressBar1.Value = 1;
progressBar1.Minimum = 0;
progressBar1.Maximum = txtList.Length;
try
{
foreach (string f in txtList)
{
string fName = Path.GetFileName(f); //f.Substring(sourceDir.Length + 1);
string destFile = Path.Combine(destDir, fName);
FileSystem.CopyFile(
f, destFile, UIOption.AllDialogs, UICancelOption.ThrowException);
progressBar1.PerformStep();
}
}
catch (IOException copyerror)
{
MessageBox.Show(copyerror.Message);
}
}
}
Note that you need to add a reference to Microsoft.VisualBasic to gain access to FileSystem.CopyFile() which copies with the standard windows UI.
I have tesseract installed and I am using button click to set location of tesseract.exe file. I am also using another button click to set the location of the image file. Now I want the third button click to process the image with tesseract as I have stored their respective locations.
I am using some basic crude approach but it suits me.
My code is like:
private void B8_Click(object sender, EventArgs e)
{
q = z + "\\" + "output.txt";
if (k != null)
{
Process pr = new Process();
pr.StartInfo.FileName = j;
pr.StartInfo.Arguments = k + " " + q;
pr.Start();
pr.WaitForExit();
}
else
{
MessageBox.Show("No Image File Selected.");
}
var filetext = File.ReadAllText(q);
tb5.Text = filetext;
//File.Delete(q);
}
private void B10_Click(object sender, EventArgs e)
{
openFileDialog1 = new OpenFileDialog();
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
j = "\"" + openFileDialog1.FileName + "\"";
MessageBox.Show("Tesseract Location Set: " + j);
}
}
private void B9_Click(object sender, EventArgs e)
{
openFileDialog1 = new OpenFileDialog();
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
k = "\"" + openFileDialog1.FileName + "\"";
MessageBox.Show("Image File Location Set: " + k);
}
}
My 3-button click story so far:
I have successfully run the code with 1-button to set the tesseract.exe path, 2-button to set the image path, but the 3-button (see B-8) has an issue.
It extracts the text and stores into an "output.txt" file. But, I am not able to import this text into my textbox tb5 and then destroy this file.
The error I am getting is Exception thrown: 'System.IO.FileNotFoundException' in mscorlib.dll
An unhandled exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll
Could not find file 'C:\Users\ambij\Desktop\try\output.txt'.
I don't understand this but there is actually output.txt file residing in the folder.
The following is for Tesseract 3.05.02 - May work in a later version
private void RunIt()
{
string tessDataPath = yourTessDataPath; // Your Tesseract Location Set
string imagePath = yourImagePath; // The Image File Location
string theTextFromTheImage = DoOCR(yourTessDataPath, yourImagePath);
// Some formatting may be required - OCR isn't perfect
MessageBox.Show(theTextFromTheImage);
}
private string DoOCR(string tessdataPath, string filePath)
{
string returnText = "";
using (var engine = new TesseractEngine(tessdataPath, "eng", EngineMode.Default))
{
// engine.SetVariable("tessedit_char_whitelist", "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"); // Only regular letters
string theVersion = engine.Version; // Optional, but useful
using (var img = Pix.LoadFromFile(filePath))
{
using (var page = engine.Process(img))
{
returnText = page.GetText();
}
}
}
return returnText;
}
I'm new to C#, I want to create a file with extension .txt and file name as with first three characters of textbox value.I am creating the file but i dont now how to store the file in the required destination for example c:\ Documents\ION.please help me.
Thank You For reading this...
private void button1_Click(object sender, EventArgs e)
{
button1.Text = "Create_File";
string fileName = textBox1.Text.Substring(0, 3) + ".txt";
File.Create(fileName);
MessageBox.Show("ok");
}
Thank U guys ,with all Your help I solved it
private void button2_Click(object sender, EventArgs e)
{
button2.Text = "SAVE";
var files = Directory.GetFiles(#"C:\\Users\\Apple\\Desktop\\proj").Length;
string fileName = textBox1.Text.Substring(0, 3) + -+ ++files + ".txt";
string path2 = Path.GetFullPath("C:\\Users\\Apple\\Desktop\\proj");
string docPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string var = Path.Combine(docPath, path2);
string var1 = Path.Combine(var, fileName);
using (StreamWriter writer = new StreamWriter(var1))
{
string var6 = textBox1.Text;
string var7 = " ";
string var8 = textBox2.Text;
string var9 = string.Concat(var6, var7, var8);
writer.WriteLine(var9);
}
MessageBox.Show("File created");
}
string fileName = textBox.Text.Substring(0,3) + ".txt";
using(StreamWriter writer = new StreamWriter(fileName))
{
writer.WriteLine("Hello world!");
}
Note that it would be wise to confirm that the TextBox contains at least three characters before doing that.
This is the same issue i had and got it solved by doing it this way :
File.WriteAllText(folderPath + "DataExport_"+srchCat_txtbox.Text+"_"+DateTime.Now.ToString("ddMMyyyy")+".csv", csv);
I needed to save CSV files with a unique name which includes a global name "DataExport", a category name "srchCat_txtbox.Text" value and the current date.
I need your help.
The thing is that my code works, it reads all the files in a folder which are 96 text files and saves the path of each file.
I then take each file and change the line number 32 in the text file which is
"Treatment";"1"; nr = 1,2,3,4,5,...,96.
My program will takes this string and replaces it with a different one, I change the first file for example to "Treatment";"100"; then the last file should be "Treatment";"196";
So to solve this i change the whole line with a new one. But when i write the number to the string first file is right when i start from 1, but files 2-10 are. 12,23,34,45,56,67,78,89, then it starts 2,3,4,5,6,7 from the 11-th file.
Why is this? My code is below.
I tried saving the integer as a string because I though i was somehow accesing a ASCII table. But that works the same, so my code is below any ideas?
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
int start = 1;
string strengur = "\";";
string myString = start.ToString();
string[] filePaths = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
//foreach (var file in Directory.EnumerateFiles(folderBrowserDialog1.SelectedPath))
for(int i = 0; i < 96 ; i++){
var lines = File.ReadAllLines(filePaths[i]);
lines[31] = "\"Treatment!!\";\"" +myString +strengur;
File.WriteAllLines(filePaths[i], lines);
start += 1;
myString = start.ToString();
}
}
}
Best Regards
Sæþór Ólafur Pétursson
Display all these files in windows explorer, sort by name, and then you will see why.
To solve it, you can set your start based on each file's line31's current number, and add by 100. E.g.:
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
string strengur = "\";";
string[] filePaths = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
foreach(var file in filePaths)
{
var lines = File.ReadAllLines(file);
int currentstart = int.Parse(lines[31].Split(';')[1].Trim('\"'));
lines[31] = "\"Treatment!!\";\"" + (currentstart+100).ToString() + strengur;
File.WriteAllLines(file, lines);
}
}
}
Edit based on your comment:
private void button1_Click(object sender, EventArgs e)
{
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
int start = 100; //set this to your user's input
string strengur = "\";";
string[] filePaths = Directory.GetFiles(folderBrowserDialog1.SelectedPath);
foreach(var file in filePaths)
{
var lines = File.ReadAllLines(file);
int currentstart = int.Parse(lines[31].Split(';')[1].Trim('\"'));
lines[31] = "\"Treatment!!\";\"" + (currentstart+start-1).ToString() + strengur;
File.WriteAllLines(file, lines);
}
}
}
I wrote a program that compiles my .cs files using csc.exe:
namespace myCompiler
{
public partial class Form1 : Form
{
string compilerFolder;
string outputFolder;
string projectFile;
string output = #" /out:";
public Form1()
{
InitializeComponent();
}
private void startCompile_Click(object sender, EventArgs e)
{
Compile();
}
public void findCompile_Click(object sender, EventArgs e)
{
DialogResult result1 = folderBrowserDialog1.ShowDialog();
compilerFolder = folderBrowserDialog1.SelectedPath;
MessageBox.Show(compilerFolder);
cscLabel.Text = compilerFolder;
}
private void outputCompile_Click(object sender, EventArgs e)
{
DialogResult result2 = folderBrowserDialog2.ShowDialog();
outputFolder = folderBrowserDialog2.SelectedPath;
outputLabel.Text = (outputFolder);
MessageBox.Show(outputFolder);
}
private void findProject_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
projectFile = openFileDialog1.FileName;
projectLabel.Text = (projectFile);
MessageBox.Show(projectFile);
}
}
public void Compile()
{
try
{
Process compile = new Process();
string outputExe = fileName.Text;
string compiler = compilerFolder + #"\csc.exe";
string arGs = output + outputFolder + #"\" + outputExe + " " + projectFile;
compile.StartInfo.FileName = (compiler);
compile.StartInfo.Arguments = (arGs);
compile.StartInfo.RedirectStandardOutput = true;
compile.StartInfo.UseShellExecute = false;
compile.Start();
string stdOutput = "";
while (!compile.HasExited)
{
stdOutput += compile.StandardOutput.ReadToEnd();
MessageBox.Show(stdOutput);
}
}
catch (Exception errorMsg)
{
MessageBox.Show(errorMsg.Message);
}
}
private void testButton_Click(object sender, EventArgs e)
{
MessageBox.Show(projectFile);
MessageBox.Show(compilerFolder);
}
}
}
The compile instruction runs but produces no results, just a quick flash of a black console screen.
Basically what seems to be happening, is when all the strings are parsed in the commandline as arguments for the process, the .cs project source directory is broken up by each white space ie c:\users\%username%\Documents\Visual Studio 2010\ is broken up as c:\users\%username%\Documents\Visual then Studio then 2010\Projects\Myproject\myproj.cs
and subsequently the compilation fails.
You need double quotes around a filepath with spaces in it.
See my edit to your code below.
public void Compile()
{
try
{
Process compile = new Process();
string outputExe = fileName.Text;
string compiler = compilerFolder + "\csc.exe";
// add double quotes around path with spaces in it.
string arGs = output + "\"" + outputFolder + "\"" + #"\" + outputExe + " " + projectFile;
compile.StartInfo.FileName = compiler;
compile.StartInfo.Arguments = arGs;
compile.StartInfo.RedirectStandardOutput = true;
compile.StartInfo.UseShellExecute = false;
compile.Start();
string stdOutput = "";
while (!compile.HasExited)
{
stdOutput += compile.StandardOutput.ReadToEnd();
MessageBox.Show(stdOutput);
}
}
catch (Exception errorMsg)
{
MessageBox.Show(errorMsg.Message);
}
}