How to automatically save *txt file while open?(or copy *txt)[C# Visual studio) - streamreader

Can somebody help?
At first, after button click I chose any *txt file in my PC(using openFileDialog), I open it and program should save it automatically(without file dialog) in BlaBla.txt. Or maybe make copy of *txt file.
I try many ways, all I get is empty blabla.txt
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
System.IO.StreamReader sr = new
System.IO.StreamReader(openFileDialog1.FileName);
string line = sr.ReadLine();
System.IO.StreamWriter file = new System.IO.StreamWriter("BlaBla.txt");
file.WriteLine(sr);
}
edidet code. Still not work.
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
System.IO.StreamReader sr = new
System.IO.StreamReader(openFileDialog1.FileName);
String line = reader.ReadLine();
// System.IO.StreamWriter file = new System.IO.StreamWriter("ddd.txt");
// file.Write(sr);
System.IO.StreamWriter file = new System.IO.StreamWriter("ddd.txt");
file.Write(sr);
file.Flush();
}_____________________________________________
Find another way to save, i`ts works.
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string org, copy;
System.IO.StreamReader file = new System.IO.StreamReader(openFileDialog1.FileName);
while ((org = file.ReadLine()) != null)
{
copy = org.ToString();
using (System.IO.StreamWriter files = new System.IO.StreamWriter("blabla.txt", true))
{
files.WriteLine(copy);
}
}
file.Close();
}

Related

Compare two text files but one doesn't exist due to permissions

I am attempting to compare two text files in a Script Task in an SSIS Package. Both files exist in the file system. Both files are in the same directory. However, one does not exist because the permissions setup do not see the file.
The code below is not working. I have tried a few different variations of the code below and the SSIS Package continues to go forward, ultimately failing on a subsequent File System Task because doesn't have access to the file.
I am attempting to capture that the file is not present because the package does not have access to the file, and not because the file isn't there. Originally, I was using File.Exists(), however, that won't work because it returns false whether the file is not there or the package does not have access to it.
string packageName = Dts.Variables["System::PackageName"].Value.ToString();
string taskName = Dts.Variables["System.TaskName"].Value.ToString();
string inputFilePath = Dts.Variables["User::inputFilePath"].Value.ToString();
string processedFilePath = Dts.Variables["User::processedFilePath"].Value.ToString();
bool blnFilesMatch = true;
try
{
int i = 0, j = 0;
// Compare the source and processed files to determine if the contents are different.
using (var f1 = new FileStream(inputFilePath, FileMode.Open))
using (var f2 = new FileStream(processedFilePath, FileMode.Open))
{
do
{
i = f1.ReadByte();
j = f2.ReadByte();
if (i != j)
break;
} while (i != -1 && j != -1);
if (i != j)
blnFilesMatch = false; // Files Differ
else
blnFilesMatch = true; // Files are the same
}
Dts.Variables["User::blnIdenticalFiles"].Value = blnFilesMatch;
Dts.TaskResult = (int)ScriptResults.Success;
}
catch (FileNotFoundException)
{
string tempFileName = "temp_" + packageName + ".txt.";
string tempFilePath = Path.Combine(Path.GetDirectoryName(inputFilePath), tempFileName);
// A file wasn't found. Try to create and delete a temp file to determine whether it was because of permissions or if the file just was not present.
try
{
File.Create(tempFilePath);
File.Delete(tempFilePath);
Dts.Variables["User::blnIdenticalFiles"].Value = false;
}
catch (UnauthorizedAccessException uae)
{
// Permissions cannot create the file.
Dts.Events.FireError(0, packageName + " - " + taskName, uae.Message, string.Empty, 0);
Dts.TaskResult = (int)ScriptResults.Failure;
}
}
catch (Exception ex)
{
Dts.Events.FireError(0, packageName + " - " + taskName, ex.Message, string.Empty, 0);
Dts.TaskResult = (int)ScriptResults.Failure;
}

How to create file in java

File Name = new File("G:/Java/lesson25_1/Name.txt");
if(Name==null){
JOptionPane.showMessageDialog(this, "Details are missing");
}
try{
FileReader fr1 = new FileReader("Name.txt");
BufferedReader br1=new BufferedReader(fr1);
String str=br1.readLine();
br1.close();
when i do this in a method it dosn't work when i click the button
There is a method for file called exists to check if the given file exist or not.
String path = "G:/Java/lesson25_1/Name.txt";
File file = new File(path);
if(!file.isFile() || !file.canRead()){
JOptionPane.showMessageDialog(this, "Details are missing");
} else {
try {
FileReader fr1 = new FileReader("Name.txt");
BufferedReader br1=new BufferedReader(fr1);
String str=br1.readLine();
br1.close();
} catch (Exception e){
e.printStackTrace();
}
}

Not able to read excel sheet saved as xls using closedxml

I have the below code to save the data in excel sheet as .xls
public ActionResult ExportToExcel()
{
DataTable tbl = CopyGenericToDataTable(res);
tbl.TableName = "InvalidInvoices";
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(tbl);
wb.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;
wb.Style.Font.Bold = true;
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename= "+fileName + ".xls");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
}
Above is code which download the xls excel sheet at client side. It works fine the data gets saved in excel sheet.
Problem is if I try to upload this same file using below code -
if (files != null)
{
HttpPostedFileBase upload = files.FirstOrDefault();
Stream stream = upload.InputStream;
DataSet result = new DataSet();
if (upload != null && upload.ContentLength > 0)
{
if (upload.FileName.EndsWith(".xls") || upload.FileName.EndsWith(".xlsx"))
{
// ExcelDataReader works with the binary Excel file, so it needs a FileStream
// to get started. This is how we avoid dependencies on ACE or Interop:
// We return the interface, so that
IExcelDataReader reader = null;
if (upload.FileName.EndsWith(".xls"))
{
reader = ExcelReaderFactory.CreateBinaryReader(stream);
}
else if (upload.FileName.EndsWith(".xlsx"))
{
reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
}
reader.IsFirstRowAsColumnNames = false;
result = reader.AsDataSet();
reader.Close();
}
}
}
In above code I am getting error in ExcelReaderFactory.CreateBinaryReader(stream);
In stream it has the values in bytes too just on using createBinaryreader of excelreaderfactory reader has error message as 'Invalid file signature'.
Any help will be highly appreciated.
ClosedXML generates .xlsx files, not .xls files.
Check your code:
Response.AddHeader("content-disposition", "attachment;filename= "+fileName + ".xls");

Error While Export To Excel in sharepoint 2010 Programmatically

The file you are trying is in a different format than specified by the file extension.Verify that the file is not corrupted and is from a trusted source before opening the file.Do you want to open the file now?
and this 'export to excel' dead the events on the page.
Here is my code
public void ExportToExcelitems(DataTable dt, string fileNameWithoutExt)
{
if (dt.Rows.Count > 0)
{
string filename = fileNameWithoutExt + ".xls";
System.IO.StringWriter tw = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
var dgGrid = new GridView();
dgGrid.DataSource = dt;
dgGrid.DataBind();
dgGrid.HeaderRow.BackColor = System.Drawing.Color.White;
dgGrid.HeaderRow.BackColor = System.Drawing.Color.White;
foreach (GridViewRow row in dgGrid.Rows)
{
row.BackColor = System.Drawing.Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = dgGrid.RowStyle.BackColor;
}
else
{
cell.BackColor = System.Drawing.Color.LightGray;
}
}
}
dgGrid.AutoGenerateColumns = false;
dgGrid.RenderControl(hw);
HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + filename + "");
this.EnableViewState = false;
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Close();
}
}
I think you should consider using OpenXML (or more specfically ClosedXML) to build a modern Excel file with the xlsx extension.
Open XML SDK: https://learn.microsoft.com/en-us/office/open-xml/open-xml-sdk
Closed XML (nuget): https://www.nuget.org/packages/ClosedXML/
Code Samples: https://github.com/ClosedXML/ClosedXML/wiki/Deliver-an-Excel-file-in-ASP.NET

How to save text files or excel files in local folder in windows phone

How to save text files or excel files in local folder in windows phone?
I get the text files from web service response from http url,
but how do I save them in a local folder?
For more ideas see my code below.
Thanks!!
Uri uri = new Uri("https://abcd/xyz/def");
WebClient wc = new WebClient();
wc.DownloadStringAsync(uri);
wc.DownloadStringCompleted += wc_DownloadStringCompleted;
void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
string result = e.Result.ToString();
MessageBox.Show(result);
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
string FolderName = "localFolder\\myData\\";
myIsolatedStorage.CreateDirectory(FolderName);
string filepath = System.IO.Path.Combine(FolderName, "myfile.txt");
using (StreamWriter write = new StreamWriter(new IsolatedStorageFileStream(filepath, FileMode.Create, FileAccess.Write, myIsolatedStorage)))
{
write.WriteLine(result);
write.Close();
}
}
Use below code to write .txtFile:
void wc_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
{
String response = e.Result.ToString();
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
//Set File Path
string FolderName = "localFolder\\myData\\";
myIsolatedStorage.CreateDirectory(FolderName);
string FilePath = System.IO.Path.Combine(FolderName, "myFile.txt");
//create new file
using (StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream(FilePath , FileMode.Create, FileAccess.Write, myIsolatedStorage)))
{
writeFile.WriteLine(response);
writeFile.Close();
}
}
And check file is saved or not:
if (myIsolatedStorage.DirectoryExists("localFolder\\myData\\"))
{
String[] fileNames = myIsolatedStorage.GetFileNames("localFolder\\myData\\*");
}

Resources