Creating a text file with user entered name using c# - c#

hi i have a webform where i am trying to create a txt file in a particular directory but i want to the name of the txt file to be entered by the user but I am not getting it how to do it please help
the code below creates a text file with name NameBox.Text.ToString I dont want that please help and thanks.
protected void Page_Load(object sender, EventArgs e)
{
NameLabel.Visible = false;
NameBox.Visible = false;
submit.Visible = false;
}
protected void Button1_Click(object sender, EventArgs e)
{
NameLabel.Visible = true;
NameBox.Visible = true;
submit.Visible = true;
}
protected void submit_Click(object sender, EventArgs e)
{
// string fname = NameBox.Text;
string path = #"D:\NameBox.Text.ToString.txt";
try
{
// Delete the file if it exists.
if (File.Exists(path))
{
// Note that no lock is put on the
// file and the possibility exists
// that another process could do
// something with it between
// the calls to Exists and Delete.
File.Delete(path);
}
// Create the file.
using (FileStream fs = File.Create(path))
{
Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
// Open the stream and read it back.
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
catch (Exception Ex)
{
Console.WriteLine(Ex.ToString());
}
}
}

First, keep in mind that your IIS will not allow you to access your local file System as you expcect in a "console" application, maybe running with local admin rights.
Second, be sware of illegal characters for file names, you need to check or replace it.
And third, what if two users decide to use the same filename?
As Dejan Dakic already mentioned, step back and reconsider, maybe about using a database, like SQLite or something else.

string path = #"D:\NameBox.Text.ToString.txt";
That won't work. if your textfield is called "NameBox" you need to access the value of its text which is not possible within a String.
Try this:
String path = #"D:\" + NameBox.Text + ".txt";
If you're new to programming, I'd suggest to go get a book or some tutorials and get started that way! :)

Related

Error trying to use a pdf file located in my project folder

I am making an application which inserts text into a pdf template, but I am encountering a problem and it is that when I want to use the template it is as if I could not find it, so I did a validation with File.Exists, and it effectively returns me false, but when I look for the same path in the file explorer it finds me the pdf without problems.
This is my code:
protected void btn_Guardar_Click(object sender, EventArgs e)
{
try
{
string newName = $"numdoc_{ddl_TipoCapacitacion.SelectedValue}-{lastId.Rows[0]["ID"]}-{DateTime.Now.ToString("dd/MM/yyyy").Replace("/", String.Empty)}.pdf";
file = Path.Combine(location, newName);
string oldFile = string.Concat(Server.MapPath($#"~/plantillasPdf/capacitaciones/plantillaDiploma.pdf"));
string newFile = string.Concat(Server.MapPath($#"~/plantillasPdf/capacitaciones/{newName}"));
if (!File.Exists(oldFile))
{
}
PdfReader reader = new PdfReader(oldFile);
...
catch (Exception ex)
{
ControlarExcepcion(ex);
}
}

Selenium find array contents on page

I'm using Visual Studio with Selenium to build an application that goes to a web page and finds if the contents of an array are on the page. I'm running into an issue with searching the page for the array contents.. Right now it finds nothing, so it clicks to go to the next page when it shouldn't.
The array comes from a CSV file I'm loading in and it needs to search the page for a match of any of the records from the CSV file and stops.
Here is what I have so far:
OpenFileDialog ofd = new OpenFileDialog();
private double timeOut;
private void bttnImportBrowse_Click(object sender, EventArgs e)
{
ofd.Filter = "CSV|*.csv";
var fileInputs = new List<string>();
if (ofd.ShowDialog() == DialogResult.OK)
{
String chosenFile = ofd.FileName;
String safeFileName = ofd.SafeFileName;
try
{
// Create an instance of StreamReader to read from a file.
// The using statement also closes the StreamReader.
using (StreamReader sr = new StreamReader(chosenFile))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
//Console.WriteLine(line);
fileInputs.Add(line);
//Console.Write(string.Join(" ", fileInputs));
var driver = new ChromeDriver(#"C:\Users\andre_000\Documents\Visual Studio 2015\Projects\MyProject\");
driver.Navigate().GoToUrl("MySite");
var WebDriverWait = new WebDriverWait(driver, TimeSpan.FromSeconds(timeOut)).Until(ExpectedConditions.ElementExists((By.XPath("/html/body/a[2]"))));
while (1==1) {
try
{
var result = driver.FindElement(By.LinkText(fileInputs.ToString()));
break;
}
catch (NoSuchElementException n)
{
var nextBttn = driver.FindElementByXPath("/html/body/a[2]");
nextBttn.Click();
}
}
}
}
}
catch (Exception entry)
{
// Let the user know what went wrong.
Console.WriteLine("The file could not be read:");
Console.WriteLine(entry.Message);
}
}
}
Sorry i would have left a comment but am not allowed to yet. Do you have the CSV file?
I believe you are trying to find the Link text incorrectly.
Currently calling ToString() on the list
var result = driver.FindElement(By.LinkText(fileInputs.ToString()));
should probably be
var result = driver.FindElement(By.LinkText(line));

C# WPF FileSaving Exception encountered

My issue is that I keep seeing a recurring theme with trying to allow my Notepad clone to save a file. Whenever I try to save a file, regardless of the location on the hard disk, the UnauthorizedAccess Exception continues to be thrown. Below is my sample code for what I've done, and I have tried researching this since last night to no avail. Any help would be greatly appreciated.
//located at base class level
private const string fileFilter = "Text Files|*.txt|All Files|*.*";
private string currentPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
private void MenuFileSaveAs_Click(object sender, RoutedEventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.DefaultExt = "*.txt";
sfd.Filter = fileFilter;
sfd.AddExtension = true;
sfd.InitialDirectory = currentPath;
sfd.RestoreDirectory = true;
sfd.OverwritePrompt = true;
sfd.ShowDialog();
try
{
System.IO.File.WriteAllText(currentPath,TxtBox.Text,Encoding.UTF8);
}
catch (ArgumentException)
{
// Do nothing
}
catch(UnauthorizedAccessException)
{
MessageBox.Show("Access Denied");
}
}
Change the following lines.
...
if (sfd.ShowDialog() != true)
return;
try
{
using (var stream = sfd.OpenFile())
using (var writer = new StreamWriter(stream, Encoding.UTF8))
{
writer.Write(TxtBox.Text);
}
}
...
I hope it helps you.
You need to get the correct path context and file object from the dialog box once the user has hit 'ok'. Namely verify the user actually hit ok and then use the OpenFile property to see what their file selection is:
if (sfd.ShowDialog.HasValue && sfd.ShowDialog)
{
if (sfd.OpenFile() != null)
{
// convert your text to byte and .write()
sfd.OpenFile.Close();
}
}

IO exception is generated when i try to copy from 1 file to other file

I create an empty file and try to copy the contents from an existing to the newly created file. When i do that i am getting an IOexception
private void button1_Click(object sender, EventArgs e)
{
String test = textBox1.Text.ToString();
if (string.IsNullOrEmpty(textBox1.Text))
{
MessageBox.Show("Enter the filename");
}
else
{
StreamWriter File = new StreamWriter(test);
MessageBox.Show(test + " Has been created");
}
}
private void button2_Click(object sender, EventArgs e)
{
String test = textBox1.Text.ToString();
try
{
File.Copy(#"D:\\Study this.txt", test);
}
catch (IOException)
{
MessageBox.Show("IO error occured");
}
}
You will need to close the Stream so in the else statement add File.Close(); that will release the newly created file. That section of the code will now look like this:
StreamWriter File = new StreamWriter(test);
File.Close();
MessageBox.Show(test + " Has been created");
replace line StreamWriter File = new StreamWriter(test); with below
using (File.Create(test)) ;
or with
using (StreamWriter writer = new StreamWriter(test)){}
reason for above change is you need to propery close the opend stream object before the copy.
using block will handle that for you.

In C# while creating a file second time will throw an exception

I am creating a file using file stream, but before that i am applying if condition to see if the file exist or not. When i click on button and if supppose file is there it deletes the file. Its ok, and again if i press the button the file gets created. At first time it works well.
Now the file is created, again if I press the button and it should delete but it is trhowing an exception saying that*The process cannot access the file 'C:\Hello1' because it is being used by another process.*
Below is my code
private void button2_Click(object sender, EventArgs e)
{
string fileName = #"C:\Hello1";
if
(File.Exists(fileName))
{
File.Delete(fileName);
MessageBox.Show("File is deleted");
}
else
{
FileInfo createFile = new FileInfo(fileName);
FileStream create = createFile.Create();
MessageBox.Show("Created");
}
}
So why I am not able to delete second time, My text file is not open also but still it is showing the exception.
You're never closing your stream that created the file. Put your FileStream in a using statement, which will automatically clean up the open file handle.
using(FileStream create = createFile.Create())
{
//code here
}
The file stream is still opened when you're trying second time, try this:
private void button2_Click(object sender, EventArgs e)
{
string fileName = #"C:\Hello1";
if
(File.Exists(fileName))
{
File.Delete(fileName);
MessageBox.Show("File is deleted");
}
else
{
FileInfo createFile = new FileInfo(fileName);
using(FileStream create = createFile.Create())
{
MessageBox.Show("Created");
}
}
}
Oh yes i got the answer,
I need to use
private void button2_Click(object sender, EventArgs e)
{
string fileName = #"C:\Hello1";
if
(File.Exists(fileName))
{
File.Delete(fileName);
MessageBox.Show("File is deleted");
}
else
{
FileInfo createFile = new FileInfo(fileName);
FileStream create = createFile.Create();
MessageBox.Show("Created");
create.Close();
}
}
We need to use create.Close();
Here is an example I used to write a local log:
StreamWriter log;
string fpath = string.Format(#"{0}\{1}.txt",GetDirectory(),DateTime.Now.ToString("yyy-MM-dd"));
if (!File.Exists(fpath))
{
log = new StreamWriter(fpath);
}
else
{
log = File.AppendText(fpath);
}
log.WriteLine(string.Format("{0} ==> {1}",DateTime.Now.ToString("MM/dd/yyy HH:mm:ss"), Message));
log.Dispose();
log = null;

Categories

Resources