WinCE 5.0 How Can I Get Directory - c#

Hi all firstly sorry for my English but i hope you can understand me..
Im doing a project on VS2008-Smart Device Project-WinCE 5.0 Project.
I need to create text file to DATA folder which is under the main directory of program.
There is my code, there is no error messege but its not creating text file.My directory always returns null.
Whats wrong with that code?
if (Form2.dosya_adi != null)
{
string cfile = Form2.chosenfile;
path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\DATA\\" + cfile+ ".txt";
}
else
{
path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase)+"\\DATA";
}
try
{
StreamReader Read_File= File.OpenText(path);//Dosyayı açmaya çalış olmaz ise catch bloğuna geç
ReadFile.Close();
}
catch
{
StreamWriter Write_File= File.CreateText(path+ i.ToString()+".txt");// yeni dosya oluştur.
Write_File.Close();
}`
And heres the form2 which includes listbox and listbox shows directory for if there is a file or not..
string path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase);
path = path + "\\DATA";
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] rgFiles = di.GetFiles();
foreach (FileInfo fi in rgFiles)
{
listBox1.Items.Add(fi.Name);
}
private void button1_Click(object sender, EventArgs e)
{
if (listBox1.SelectedItem != null)
{
chosen_file = listBox1.GetItemText(listBox1.SelectedItem);
Form1 form1 = new Form1();
form1.Show();
this.Hide();
}
else
{
MessageBox.Show("HATA:Hiçbir Değer Seçilmedi!"); // That means error:no value chosen!
}
}

Your code does not prepare the path variable properly. In one case it contains a file name, in another case it contains only a path name:
if (Form2.dosya_adi != null)
{
string cfile = Form2.chosenfile;
path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase) + "\\DATA\\" + cfile+ ".txt";
}
else
{
path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase)+"\\DATA";
}
Then you try to open a file - even though the variable does not contain a file name in the first place. If that leads to an exception, you try to create a file, but actually, you're not adding a path separator to the path. So I think your catch block should read:
StreamWriter Write_File= File.CreateText(path + "\\" + i.ToString() + ".txt");// yeni dosya oluştur.
Write_File.Close();

Related

save the content of the text box to a variable c#

I have the following method in windows form
private void btnSelectNuevo_Click(object sender, EventArgs e)
{
if (openFileDialog2.ShowDialog() == DialogResult.OK)
{
try
{
string fichero = openFileDialog2.FileName.ToString();
txtbox_sel_fich.Text = fichero;
if (string.IsNullOrEmpty(txtbox_sel_fich.Text) == true)
{
MessageBox.Show("file not selected", "return file selection", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
}
catch (SecurityException ex)
{
MessageBox.Show($"Security error.\n\nError message: {ex.Message}\n\n" +
$"Details:\n\n{ex.StackTrace}");
}
}
}
and another method:
private void btnsubir_Click(object sender, EventArgs e)
{
string reply = "";
string fichero = "";
fichero = textbox_select.Text.ToString();
// string ruta = textbox_select.Text.ToString();
// FileInfo fich = new FileInfo(ruta);
// fichero = fich.Name;
if (fichero == readLastFile(fichero))
{
createLog(fichero + ":this file" + fichero + " You have already been imported previously. No action is realized\n");
MessageBox.Show("This file" + "'" + fichero + "'" + " You have already been imported");
}
else
{..
how can you see I have a method called "readLastFile (fichero)"; what it does is check in MySql in the "File" table if there is a file already imported with that name that I pass as a parameter, if it exists it does not import it to the DDBB and the program ends but if it does not exist it does the import.
The problem I have is that the file variable stores the entire path of an excel file (c: \ ... \ helloWord.xlsx) when what I want is that it only stores (helloWord.xlsx) since when I am going to do the check tells me it doesn't exist and starts loading when it shouldn't.
Some help?
I don't know if I am saving it correctly. THANKS FOR YOUR SUPPORT
I have is that the file variable stores the entire path of an excel file (c: \ ... \ helloWord.xlsx) when what I want is that it only stores (helloWord.xlsx)
Use Path.GetFileName(...)
Path is part of the System.IO namespace

How do I store the Directory name chosen from FolderBrowserDialog() in wpf?

I have a "settings" button in one of my programs that will be used to grab a directory that the user wants to work with.
After they select a directory, I'd like to be able to return three pieces of information.
The name of the directory chosen.
The number of files in that directory (just files, not other directories)
A list with the names of every file in the directory.
I have been looking through this page, and I found the GetFiles() method, but I haven't figured out how to get the name of the directory. Any nudge in the right direction is appreciated.
Here's what I have so far.
public void SettingsButton(object sender, RoutedEventArgs e)
{
var dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
string[] files = Directory.GetFiles(dialog.SelectedPath);
MessageBox.Show("files found" + files.Length.ToString(), "Message");
}
}
I know the code above doesn't return the names of the files, but I know the rough idea on how to do that, I just haven't implemented it yet....so my questions just about storing the directory they chose as a string.
here's an example how you can do this, a simple foreach:
public void SettingsButton(object sender, RoutedEventArgs e)
{
var dialog = new System.Windows.Forms.FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dialog.ShowDialog();
if (result == System.Windows.Forms.DialogResult.OK)
{
string[] files = Directory.GetFiles(dialog.SelectedPath);
string resultStr = string.Empty;
foreach (String item in files)
{
resultStr += item.ToString() + "\n";
}
MessageBox.Show("path:" + dialog.SelectedPath + "\n" +
"files: " + files.Count().ToString() + "\n" +
resultStr, "Message");
}
}
using System.Windows.Forms;
FolderBrowserDialog() dialog = new FolderBrowserDialog();
DialogResult result = dialog.ShowDialog();
Here result will have the selected folder.

How do I save some files under a directory in a new directory after making some changes

I opened a directory and I read some files in that directory amd made some changes, now I want to save the changes with the same file names at F:\BI\Out\ and keep the original files.
when I added these two lines
var outFilePath = #"F:\BI\Out\" + Path.GetFileName(file);
File.WriteAllText(outFilePath, text);
I was able to save the files under the new folder\Out,
but when I opened them I found that only one file is changed correctly and all the other files the old words are replace by blank space not by the new words.
Can anyone help me Thanks
string text = "";
string[] files;
private void Form1_Load(object sender, EventArgs e)
{
try
{
files = Directory.GetFiles(#"F:\BI\In\", "*.*", SearchOption.AllDirectories);
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
this.Close();
}
}
private void btnUpdate_Click(object sender, EventArgs e)
{
if (txtEtlPath.Text == "")
{
MessageBox.Show("Please Enter path");
txtEtlPath.Focus();
}
else
{
foreach (string file in files)
{
if (System.IO.File.Exists(file))
{
text = File.ReadAllText(file);
text = text.Replace("Company_Address", txtCompanyAddress.Text + "_BI");
text = text.Replace("Company_Name", txtCompanyName.Text.Trim() + "_BIDW");
text = text.Replace("C:\\BIfolder",cboDrive.Text + txtEtlPath.Text.Trim());
var outFilePath = #"F:\BI\Out\" + Path.GetFileName(file);
File.WriteAllText(outFilePath, text);
}
Within your foreach () loop:
If you want the subfolder structure of the files found, do a replace on the filepath:
var outFilePath = file.Replace(#"F:\BI\In\", #"F:\BI\Out\");
You will need to create the subfolder before you can write the changed file:
new FileInfo(outFilePath)).Directory.Create();
If you don't want the subfolders, you can write directly into the top folder:
var outFilePath = #"F:\BI\Out\" + Path.GetFileName(file);
Writing is simple, just keep in mind there is an optional encoding parameter:
File.WriteAllText(outFilePath, text);

Find a file in my directory

I need to get the path of a file which is in a specific directory.The user selects a csv file from a OpenFileDialog. If the csv file has field that ends at .txt then take the path of that file and put it in a pathfile variable. The new file has to be placed, by the user, in the same directory as the csv file.
EDIT: How do I put the path of the file in a variable ?
EDIT2: The file could be placed everywhere, for example: C://george.csv. So I want to take a txt from the directory c:// .Or if the file is here: C://Documents/anna.csv. The text has to be C://Documents/textfile.txt.
EDIT3: The csv file that the user has opened is at c://Documents/gonow.csv
The file gonow.csv is : one, two, tree, four, textfile.txt, five, six, seven.
When a field has extension .txt then the program has to go and cath the path. In this case the path is c://Documents/textfile.txt.
private void button3_Click(object sender, EventArgs e)
{
string filename = "";
DialogResult result = openFileDialog2.ShowDialog();
if (result == DialogResult.OK)
{
filename = openFileDialog2.FileName;
textBox3.Text = filename;
System.IO.StreamReader file2 = new System.IO.StreamReader(textBox3.Text);
}
}
private void button2_Click(object sender, EventArgs e)
{
if (Path.GetExtension(colB[j]) == ".csv")
textBox2.Text += " comma separated, in line " + j + "" + Environment.NewLine;
}
Try
string path = Path.GetDirectoryName(filename);
EDITED according to your EDIT3:
Use this function to open your csv file and get new complete filename.
private string GetFilename(string csvFilename)
{
string path = Path.GetDirectoryName(csvFilename);
string[] lines = File.ReadAllLines(csvFilename);
foreach (string line in lines)
{
string[] items = line.Split(',');
string txt = items.First(item => item.ToLower().Trim().EndsWith(".txt"));
if (!String.IsNullOrEmpty(txt))
return Path.Combine(path, txt);
}
return "";
}
iF you need to put the txt file (the generated file) in the same folder as that of the CSV file, you can store the path of the CSV file and create the txt file in theat folder.
To do this you may like to have a variable like this:
private void button3_Click(object sender, EventArgs e)
{
string filename = "";
string FolderPath;
DialogResult result = openFileDialog2.ShowDialog();
if (result == DialogResult.OK)
{
filename = openFileDialog2.FileName;
FolderPath = Path.GetDirectoryName(filename);
textBox3.Text = filename;
System.IO.StreamReader file2 = new System.IO.StreamReader(textBox3.Text);
}
}
private void button2_Click(object sender, EventArgs e)
{
if (Path.GetExtension(colB[j]) == ".csv")
textBox2.Text += " comma separated, in line " + j + "" + Environment.NewLine;
}
The FolderPAth variable holds the path to the folder. You can create the txt file in this folder. This means that the txt file is in the same folder as of the csv file. If you need to access this in a different method, you may declare it in relevant scope.

C# WinForms - Error on OpenFileDialog MultiSelect: "Index was outside the bounds of the array."

In debug mode, while running the C# WinFOrms App, After I select the files through the OpenFileDialog, I get the
Error: Could not read file from disk.
Original error: Index was outside the bounds of the array.
Do you have any idea on how to fix this Error?
Here's my code:
// When the user clicks on Select Files Button, this happens
private void sourceFiles_Click(object sender, EventArgs e)
{
Stream myStream;
int i = 0;
OpenFileDialog sourceFileOpenFileDialog = new OpenFileDialog();
this.sourceFileOpenFileDialog.InitialDirectory = "i:\\CommissisionReconciliation\\Review\\";
this.sourceFileOpenFileDialog.Filter = "Excel Files (*.xls;*.xlsx;)|*.xls;*.xlsx;|" + "All Files (*.*)|*.*";
this.sourceFileOpenFileDialog.FilterIndex = 2;
this.sourceFileOpenFileDialog.RestoreDirectory = true;
this.sourceFileOpenFileDialog.Multiselect = true;
this.sourceFileOpenFileDialog.Title = "Please Select Excel Source File(s) for Consolidation";
if (this.sourceFileOpenFileDialog.ShowDialog() == DialogResult.OK)
{
try
{
string tempFolder = System.IO.Path.GetTempPath();
foreach (string FileName in this.sourceFileOpenFileDialog.FileNames)
{
this.sourceFileOpenFileDialog.FileNames[i] = FileName;
listBoxSourceFiles.Items.Add(FileName);
Log("Source Files: " + sourceFileOpenFileDialog.FileNames[i]);
i++;
System.IO.File.Copy(FileName, tempFolder + #"\" + FileName);
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
//method for the sourcefileOpenFileDialog. Do I need anything here?
private void sourceFileOpenFileDialog_FileOk(object sender, CancelEventArgs e)
{
}
//method for the listbox. Do I need anything here?
private void listBoxSourceFiles_SelectedIndexChanged(object sender, EventArgs e)
{
}
Thanks!
What you are doing doesn't seem to make a lot of sense. What is the following line supposed to do?
this.sourceFileOpenFileDialog.FileNames[i] = FileName;
Just change your foreach to this:
foreach (string FileName in this.sourceFileOpenFileDialog.FileNames)
{
listBoxSourceFiles.Items.Add(FileName);
Log("Source Files: " + FileName);
System.IO.File.Copy(FileName, Path.Combine(tempFolder, Path.GetFileName(FileName)));
}
The error arises from the fact, that you have two variables named sourceFileOpenFileDialog. One is a member of your class and one is declared inside the method.
The one that is declared inside the method is only ever used in the following line:
Log("Source Files: " + sourceFileOpenFileDialog.FileNames[i]);
Because this instance is not used to show the dialog to the user, its FileNames property has a Length of 0 and therefore trying to access any items in it results in the exception.
Update:
There is one more problem:
FileName is a complete path, so appending it to the temp path will result in an invalid path. Also, consider using Path.Combine to combine two paths:
Path.Combine(tempFolder, Path.GetFileName(FileName))

Categories