Delete word in textbox - c#

user write some sentence in textbox then i want to delete word in sentence after that save the file.
for example user write
hi my name is john
it should be output
hi my is john
string lines = saveTxtBox.Text;
string newLines;
//string removedBreaks = Line.Replace("\r\n", replaceWith).Replace("\n", replaceWith).Replace("\r", replaceWith);
newLines = lines.Replace("name"," ");
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Text Documents (*.txt)|*.txt|All files (*.*)|*.*";
sfd.FileName = DateTime.Now.ToShortDateString();
if (sfd.ShowDialog() == DialogResult.OK)
{
ToTxt(newLines, sfd.FileName);
}
but its just save the file i cannot delete name word.

I tried this, it worked just fine.
string lines = saveTxtBox.Text;
string newLines = lines.Replace("YNATEXT.", " ");
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Text Documents (*.txt)|*.txt|All files (*.*)|*.*";
sfd.FileName = DateTime.Now.ToShortDateString();
if (sfd.ShowDialog() == DialogResult.OK)
{
System.IO.File.WriteAllText(sfd.FileName, newLines);
}
Do remember that you need to have that EXACT string YNATEXT. (with a period in the end) for it to replace it.

Related

How do I get directory of multiple files in multiple variables?

I want to read 2 excel files from the same directory and store their full paths in two different variables.
For example,
C:\\Users\\User\\Desktop\\Folder\\File1.xlsx - First value
C:\\Users\\User\\Desktop\\Folder\\File2.xlsx - Second value
I am taking a string array for this but it is not working.
Please help.
I have done the following:
string[] location = new string[2];
int i = 0;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
this.openFileDialog1.Filter = "Excel|*.xlsx;*.xlxm;*.xls | All files (*.*)|*.*";
this.openFileDialog1.Multiselect = true;
this.openFileDialog1.Title = "Select Excel Files";
DialogResult dr = this.openFileDialog1.ShowDialog();
if (dr == System.Windows.Forms.DialogResult.OK)
{
foreach (String file in openFileDialog1.FileNames)
{
location[i] = Path.GetDirectoryName(file);
i++;
}
}
The only thing I can see wrong with your code is you are creating a local instance of OpenFileDialog and then trying to reference it as if it were a class member field.
OpenFileDialog openFileDialog1 = new OpenFileDialog();
this.openFileDialog1.Filter = "Excel|*.xlsx;*.xlxm;*.xls | All files (*.*)|*.*";
Get rid of this.
Your code is very risky of crashing in case user does select more than one file. I see no reason why to set the array size of "location" directly to two.
I recommend you to check the comment from Alex K. The .FileNames -property of the dialog already is an array. And getting the directory, will then be the same for all (like Crowcoder wrote).
I assume, what you need at the end is this:
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "Excel|*.xlsx;*.xlxm;*.xls | All files (*.*)|*.*";
openFileDialog1.Multiselect = true;
openFileDialog1.Title = "Select Excel Files";
DialogResult dr = openFileDialog1.ShowDialog();
if (dr == System.Windows.Forms.DialogResult.OK)
{
string[] location = openFileDialog1.FileNames;
// do something
}
And if in case, you need the directory, do this:
string[] location = openFileDialog1.FileNames.Select(x => Path.GetDirectoryName(x)).ToArray()

C# - System.IO.IOException

I have a method that saves the text from a text box into a txt file but I get an System.IO.IOException error every time I back out of the SaveFileDialog.
static OpenFileDialog ofd = new OpenFileDialog();
static SaveFileDialog sfd = new SaveFileDialog();
static String cp;
private void SaveClass() {
sfd.DefaultExt = "txt";
sfd.Filter = "Text Files | *.txt";
if (sfd.ShowDialog() == DialogResult.OK) {
cp = sfd.FileName;
File.Create(cp);
File.WriteAllLines(#cp, StudentTextBox.Text.Split(new String[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries));
}
}
Visual Studio highlights the code that starts with "File.WriteAllLines" and says that's where I'm getting the error. Thanks.
Exact error message:
An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll
Additional information: The process cannot access the file 'C:\Users\ktfjulien\Documents\poop.txt' because it is being used by another process.
EDIT:
Thank you, I no longer get the error message but everything I save into the text box is written onto one line, regardless if the text is delimited by new lines or not.
You do not need to do File.Create(cp); to write to a file. This is the cause of the error. Instead, directly do:
cp = sfd.FileName;
FileStream fs = File.OpenWrite(cp);
And if you want to use the StreamWriter instead of FileStream, use the FileStream as the input for your StreamWriter
StreamWriter sw = new StreamWriter(fs);
Or, you could also directly use File.WriteAllLines as you show - don't use the File.Create:
if (sfd.ShowDialog() == DialogResult.OK) {
cp = sfd.FileName;
//File.Create(cp); //remove this
File.WriteAllLines(#cp, StudentTextBox.Text.Split(new String[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries));
}
When you are creating file using File.Create() this file is already used by File.Create() you need close that file before use another place so before writing text to the file close file writer
var file = File.Create(cp);
file.Close();
complete working solution
static OpenFileDialog ofd = new OpenFileDialog();
static SaveFileDialog sfd = new SaveFileDialog();
static String cp;
private void SaveClass()
{
sfd.DefaultExt = "txt";
sfd.Filter = "Text Files | *.txt";
if (sfd.ShowDialog() == DialogResult.OK)
{
cp = sfd.FileName;
var file = File.Create(cp);
file.Close();
File.WriteAllLines(#cp, StudentTextBox.Text.Split(new String[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries));
}
}
You have no need to create the file, File.WriteAllLines will do it for you (or clear up the file if it exists):
private void SaveClass() {
sfd.DefaultExt = "txt";
sfd.Filter = "Text Files | *.txt";
if (sfd.ShowDialog() == DialogResult.OK)
File.WriteAllLines(sfd.FileName, StudentTextBox.Text
.Split(new String[] { Environment.NewLine },
StringSplitOptions.RemoveEmptyEntries));
}

C# SaveFileDialog

I am using the savefiledialog to save a file. Now I need to check if the name already exists.
If it exists the user needs to get a chance to change the name or overwrite the already existing file.
I have tried it with everything and searched a lot but can't find a solution while I technically think it should be easy to do. In the if (File.Exists(Convert.ToString(infor)) == true) the check must take place.
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = ".xlsx Files (*.xlsx)|*.xlsx";
if (sfd.ShowDialog() == DialogResult.OK)
{
string path = Path.GetDirectoryName(sfd.FileName);
string filename = Path.GetFileNameWithoutExtension(sfd.FileName);
for (int i = 0; i < toSave.Count; i++)
{
FileInfo infor = new FileInfo(path + #"\" + filename + "_" + exportlist[i].name + ".xlsx");
if (File.Exists(Convert.ToString(infor)) == true)
{
}
toSave[i].SaveAs(infor);
MessageBox.Show("Succesvol opgeslagen als: " + infor);
}
}
Just use the OverwritePrompt property of SaveFileDialog:
SaveFileDialog sfd = new SaveFileDialog{ Filter = ".xlsx Files (*.xlsx)|*.xlsx",
OverwritePrompt = true };
MSDN link on OverwritePrompt can be found here.
do this instead
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = ".xlsx Files (*.xlsx)|*.xlsx";
sfd.OverwritePrompt = true;
That should do the work for you
I would use an approach like this:
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = ".xlsx Files (*.xlsx)|*.xlsx";
do
{
if (sfd.ShowDialog() == DialogResult.OK)
{
string path = Path.GetDirectoryName(sfd.FileName);
string filename = Path.GetFileNameWithoutExtension(sfd.FileName);
try
{
toSave[i].SaveAs(infor);
break;
}
catch (System.IO.IOException)
{
//inform user file exists or that there was another issue saving to that file name and that they'll need to pick another one.
}
}
} while (true);
MessageBox.Show("Succesvol opgeslagen als: " + infor);
Catching an exception instead of using File.Exists is really the only way to do it, because something external could create the file between File.Exists and actually writing it, thus throwing an exception you'd have to handle anyway.
This code will loop and continue to prompt the user until the file is successfully written.

How to give custom made locations for downloading the file

I just wanted to know how can i give a custom made default location for grabbing the files.
I have uploaded a file to the local database and i have binded the file to the gird also. When i press download its showing an error called "the file is not found in location"
If i copy the particular uploaded files to the specified location i can download it easily.
So i just need to know how can i give a default location so that i can upload and downlaod the file from the same exact location.
snapshot of error: https://imageshack.com/i/ewTrmAI2j
Edited the same below code with custom made folder path. But i dont know why the file is always being asked from bin/debug/ folder. WHy its happening like this. IS there any way i can make changes to this folder.. other than bin/debug/ folder
Codes:
private void DownloadAttachment(DataGridViewCell dgvCell)
{
string fileName = Convert.ToString(dgvCell.Value);
//Return if the cell is empty
if (fileName == string.Empty)
return;
FileInfo fileInfo = new FileInfo(fileName);
string fileExtension = fileInfo.Extension;
byte[] byteData = File.ReadAllBytes(fileInfo.FullName); - - - - <<<<< ERROR HERE
//show save as dialog
using (SaveFileDialog saveFileDialog1 = new SaveFileDialog())
{
//Set Save dialog properties
saveFileDialog1.Filter = "Files (*" + fileExtension + ")|*" + fileExtension;
saveFileDialog1.Title = "Save File as";
saveFileDialog1.CheckPathExists = true;
saveFileDialog1.FileName = fileName;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string s = cncInfoDataGridView.Rows[dgvCell.RowIndex].Cells[1].Value.ToString();
File.WriteAllBytes(saveFileDialog1.FileName, byteData);
byteData = System.Text.Encoding.ASCII.GetBytes(s);
}
}
}
The FileInfo() constructor only works with a full file path. It sounds like you are trying to use the constructor with just a file name, at which point it fails when you try to read the file because its not a valid path. There are a couple possibilities for dealing with this:
Create your own MyFileInfo() class inheriting from FileInfo() and add a constructor that appends your specific path to the filename.
Simply append the path in-line in your code as:
var myPath = #"c:\folder\stuff\";
FileInfo fileInfo = new FileInfo(myPath + fileName);
Normally the path would be setup as a setting in your app.config so you could change it easily if needed.
I found the answer
codes for the binding file path to the gridview and download the file using the file path
private void UploadAttachment(DataGridViewCell dgvCell)
{
using (OpenFileDialog fileDialog = new OpenFileDialog())
{
//Set File dialog properties
fileDialog.CheckFileExists = true;
fileDialog.CheckPathExists = true;
fileDialog.Filter = "All Files|*.*";
fileDialog.Title = "Select a file";
fileDialog.Multiselect = true;
if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string strfilename = fileDialog.FileName;
cncInfoDataGridView.Rows[dgvCell.RowIndex].Cells[1].Value = strfilename;
}
}
}
/// <summary>
/// Download Attachment from the provided DataGridViewCell
/// </summary>
/// <param name="dgvCell"></param>
private void DownloadAttachment(DataGridViewCell dgvCell)
{
string fileName = Convert.ToString(dgvCell.Value);
if (!string.IsNullOrEmpty(fileName))
{
byte[] objData;
FileInfo fileInfo = new FileInfo(fileName);
string fileExtension = fileInfo.Extension;
//show save as dialog
using (SaveFileDialog saveFileDialog1 = new SaveFileDialog())
{
//Set Save dialog properties
saveFileDialog1.Filter = "Files (*" + fileExtension + ")|*" + fileExtension;
saveFileDialog1.Title = "Save File as";
saveFileDialog1.CheckPathExists = true;
saveFileDialog1.FileName = fileName;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
string s = cncInfoDataGridView.Rows[dgvCell.RowIndex].Cells[1].Value.ToString();
objData = File.ReadAllBytes(s);
File.WriteAllBytes(saveFileDialog1.FileName, objData);
}
}
}
}
}

Export C# reportviewer control programmatically

Does anyone know if you can programmatically save a report shown in a reportviewer control in C#?
When a report is shown there are "Export to..." buttons and I would like to automate the saving to PDF function.
You can do this with ReportViewer Control(with LocalReport.Render Method), check "Email a report" example at the http://www.gotreportviewer.com/
string _sPathFilePDF = String.Empty;
String v_mimetype;
String v_encoding;
String v_filename_extension;
String[] v_streamids;
Microsoft.Reporting.WinForms.Warning[] warnings;
string _sSuggestedName = String.Empty;
Microsoft.Reporting.WinForms.ReportViewer reportViewer1;
Microsoft.Reporting.WinForms.LocalReport objRDLC = new Microsoft.Reporting.WinForms.LocalReport();
reportViewer1.LocalReport.ReportEmbeddedResource = "reportViewer1.rdlc";
reportViewer1.LocalReport.DisplayName = _sSuggestedName;
objRDLC.DataSources.Clear();
byte[] byteViewer = rptvFlightPlan.LocalReport.Render("PDF", null, out v_mimetype, out v_encoding, out v_filename_extension, out v_streamids, out warnings);
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "*PDF files (*.pdf)|*.pdf";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
saveFileDialog1.FileName = _sSuggestedName;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
FileStream newFile = new FileStream(saveFileDialog1.FileName, FileMode.Create);
newFile.Write(byteViewer, 0, byteViewer.Length);
newFile.Close();
}
You can't export to an event as far as reportviewer in web forms are concerned.

Categories

Resources