I wanted to write a text to file using StreamWriter.But Filename should be current date name.
here is my coding.Can somebody tell me how to specify the file creation path?
Code Edit :
In here i wanted to create a .txt file but in here file not created.
public void WriteToFile( string name, string source, int dest, string messageIn, string operatorNew)
{
string directory = ResolveUrl("~/DesktopModules/SMSFunction/SMSText");
string filename = String.Format("{0:yyyy-MM-dd}__{1}", DateTime.Now,name);
string path = Path.Combine(directory, filename);
if (!File.Exists(filename))
{
using (StreamWriter str = File.CreateText(path))
{
str.WriteLine("msisdn: " + source);
str.WriteLine("shortcode : " + dest);
str.WriteLine("Message : " + messageIn);
str.WriteLine("Operator :" + operatorNew);
str.Flush();
}
}
else if (File.Exists(filename))
{
using (var str = new StreamWriter(filename))
{
str.WriteLine("msisdn: " + source);
str.WriteLine("shortcode : " + dest);
str.WriteLine("Message : " + messageIn);
str.WriteLine("Operator :" + operatorNew);
str.Flush();
}
}
you need to make following changes
1.Replace ResolveUrl with Server.MapPath
string directory = Server.MapPath("~/DesktopModules/SMSFunction/SMSText");
2.Add the file extension .txt as shown below
string filename = String.Format("{0:yyyy-MM-dd}__{1}.txt", DateTime.Now,name);
3.when you are checking whether file exists or not provide the path of the file , instead of filename
File.Exists(path);
4.under the else if block , here also provide the path , instead of filename
var str = new StreamWriter(path));
putting all together the code looks like,
string directory = Server.MapPath("~/DesktopModules/SMSFunction/SMSText");
string filename = String.Format("{0:yyyy-MM-dd}__{1}.txt", DateTime.Now, name);
string path = Path.Combine(directory, filename);
if (!File.Exists(path))
{
using (StreamWriter str = File.CreateText(path))
{
str.WriteLine("msisdn: " + source);
str.WriteLine("shortcode : " + dest);
str.WriteLine("Message : " + messageIn);
str.WriteLine("Operator :" + operatorNew);
str.Flush();
}
}
else if (File.Exists(path))
{
using (var str = new StreamWriter(path))
{
str.WriteLine("msisdn: " + source);
str.WriteLine("shortcode : " + dest);
str.WriteLine("Message : " + messageIn);
str.WriteLine("Operator :" + operatorNew);
str.Flush();
}
File.Create returns FileStream, and you need StreamWriter. You'll have to use its constructor that accepts Stream:
using (var str = new StreamWriter(File.CreateText(path)))
Simplify, use FileStream to create or overwrite your file (see below) depending on your neeeds you might want to change the FileMode to be something else (Append ?)
public void WriteToFile(string name, string source, int dest, string messageIn, string operatorNew)
{
string directory = ResolveUrl("~/DesktopModules/SMSFunction/SMSText");
string filename = String.Format("{0:yyyy-MM-dd}__{1}", DateTime.Now,name);
string path = Path.Combine(directory, filename);
using (FileStream fs = new FileStream(path, FileMode.Create))
{
using (StreamWriter str = new StreamWriter(fs))
{
str.WriteLine("msisdn: " + source);
str.WriteLine("shortcode : " + dest);
str.WriteLine("Message : " + messageIn);
str.WriteLine("Operator :" + operatorNew);
str.Flush();
}
}
}
Let's say your console app project name is DataPrep. Now you can write in Data directory location by creating a new file namely as db.json
string filePath = Path.GetFullPath(Path.Combine(Environment.CurrentDirectory, #"..\..\..\")) + #"Data\db.json";
if (!File.Exists(filePath))
{
using (StreamWriter _streamWriter = File.CreateText(filePath))
{
_streamWriter.Write(resultAll);
_streamWriter.Flush();
}
}
else if (File.Exists(filePath))
{
using (var _streamWriter = new StreamWriter(filePath))
{
_streamWriter.Write(resultAll);
_streamWriter.Flush();
}
}
Related
I have an error with database file path, the project has many databases with 10 tables, for each file should have 1 database, I create a database but it can't be saved as file ... and the error is:
The File Path Is Not Supported ...
public class filewrite
{
public string datadress, dataname, databaseadress, tablexist, dsname, databak, dataldf, databakldf, filepath, filename;
public filewrite()
{
databaseadress = "baseadress";
dataname = "name";
datadress = "adress";
dsname = "databasename1";
databak = "backUp";
tablexist = "yesorno";
dataldf = "dl";
databakldf = "dbl";
filepath = "path";
filename = "name";
}
public byte writing()
{
if (File.Exists(filepath + #"\" + filename + #"\Data" + datadress))
File.Delete(filepath + #"\" + filename + #"\Data" + datadress);
if (File.Exists(#"C:\tempFile.SMP"))
File.Delete(#"C:\tempFile.SMP");
string path = filepath + #"\" + filename + #"\Data" + datadress;
FileStream fpath = File.Create(path);(The error is in here)
try
{
// read from file or write to file
StreamWriter fwrite = new StreamWriter(fpath);
fwrite.WriteLine(datadress);
fwrite.WriteLine(dataname);
fwrite.WriteLine(databaseadress);
fwrite.WriteLine(tablexist);
fwrite.WriteLine(dsname);
fwrite.WriteLine(databak);
fwrite.WriteLine(dataldf);
fwrite.WriteLine(databakldf);
fwrite.Close();
}
finally
{
}
File.Copy(filepath + #"\" + filename + #"\Data" + datadress, #"C:\tempFile.SMP");
return 10;
}
}
Rather than using filepath + #"\" + filename + #"\Data" + datadress;,
Try using System.IO.Path.Combine instead:
Path.Combine(filepath, fileName, Data, datadress);
which returns a string.
I With Code my application added to startup
how I can after Creation File (filename + ".url") Change To (filename + ".exe")
static string filename = "troj";
public static string tempure = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\" + filename + ".exe";
public static string tempurepath = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\";
public static void addtostart()
{
try
{
string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.Startup);
if (System.IO.File.Exists(deskDir + "\\" + filename + ".url")) return;
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(deskDir + "\\" + filename + ".url"))
{
string app = tempure;
writer.WriteLine("[InternetShortcut]");
writer.WriteLine("URL=file:///" + app);
writer.WriteLine("IconIndex=0");
string icon = app.Replace('\\', '/');
writer.WriteLine("IconFile=" + icon);
writer.Flush();
}
}
catch
{
So, I am trying to create a file at a specific path but the code I have doesn't allows me to create folders.
This is the code I have:
public void LogFiles()
{
string data = string.Format("LogCarga-{0:yyyy-MM-dd_hh-mm-ss}.txt", DateTime.Now);
for (int linhas = 0; linhas < dataGridView1.Rows.Count; linhas++)
{
if (dataGridView1.Rows[linhas].Cells[8].Value.ToString().Trim() != "M")
{
var pathWithEnv = #"%USERPROFILE%\AppData\Local\Cargas - Amostras\_logs\";
var filePath = Environment.ExpandEnvironmentVariables(pathWithEnv);
using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
{
using (StreamWriter writer = File.AppendText(filePath + data))
{
string carga = dataGridView1.Rows[linhas].Cells[0].Value.ToString();
string referencia = dataGridView1.Rows[linhas].Cells[1].Value.ToString();
string quantidade = dataGridView1.Rows[linhas].Cells[2].Value.ToString();
string dataemissao = dataGridView1.Rows[linhas].Cells[3].Value.ToString();
string linha = dataGridView1.Rows[linhas].Cells[4].Value.ToString();
string marca = dataGridView1.Rows[linhas].Cells[5].Value.ToString().Trim();
string descricaoweb = dataGridView1.Rows[linhas].Cells[6].Value.ToString().Trim();
string codprod = dataGridView1.Rows[linhas].Cells[7].Value.ToString().Trim();
string tipoemb = dataGridView1.Rows[linhas].Cells[8].Value.ToString().Trim();
string nomepc = System.Environment.MachineName;
writer.WriteLine(carga + ", " + referencia + ", " + quantidade + ", " + dataemissao + ", " + linha + ", " + marca + ", " + descricaoweb + ", " + codprod + ", "
+ tipoemb + ", " + nomepc);
}
}
}
}
}
This %USERPROFILE%\AppData\Local\ in the universal path and I want to automatically create the \Cargas - Amostras\_logs\.
Do you have any idea how to do it?
The simpelest solution is replace
using (FileStream fs = new FileStream(filePath, FileMode.OpenOrCreate))
with
System.IO.Directory.CreateDirectory(filePath)
That will create the directory if it does not exist or do nothing if it does.
You need to create two checks, for your first folder and then second directory.
var pathWithEnv = #"%USERPROFILE%\AppData\Local\Cargas - Amostras\";
if (System.IO.Directory.Exists(pathWithEnv))
{
pathWithEnv = System.IO.Path.Combine(pathWithEnv, #"_logs\");
if (System.IO.Directory.Exists(pathWithEnv))
{
//Do what you want to do, both directories are found.
}
else
{
System.IO.Directory.CreateDirectory(pathWithEnv);
//Do what you want to do, both directories are available.
}
}
else
{
System.IO.Directory.CreateDirectory(pathWithEnv);
pathWithEnv = System.IO.Path.Combine(pathWithEnv, #"_logs\");
if (System.IO.Directory.Exists(pathWithEnv))
{
//Do what you want to do, both directories are available now.
}
else
{
System.IO.Directory.CreateDirectory(pathWithEnv);
//Do what you want to do, both directories are created.
}
}
I'm using Streamwriter to save my list data to a text file, but the file is always empty when I open it.
I can get the list to display all of the inputs, so the list works. Heres the code for the filewriter.
private void SaveToFile()
{
string taxpayerLine;
string taxpayerFile;
string myFileName;
FileInfo myFile;
SaveFileDialog taxpayerFileChooser;
StreamWriter fileWriter;
taxpayerFileChooser = new SaveFileDialog();
taxpayerFileChooser.Filter = "All text files|*.txt";
taxpayerFileChooser.ShowDialog();
taxpayerFile = taxpayerFileChooser.FileName;
taxpayerFileChooser.Dispose();
fileWriter = new StreamWriter(taxpayerFile, true);
foreach (Taxpayer tp in Taxpayers)
{
taxpayerLine = tp.Name + "," +
tp.Salary.ToString() + "," +
tp.InvestmentIncome.ToString() + "," +
(tp.InvestmentIncome + tp.Salary).ToString() + "," +
tp.GetRate().ToString() + "," +
tp.GetTax().ToString();
fileWriter.WriteLine(taxpayerLine);
}
fileWriter.Close();
fileWriter.Dispose();
myFile = new FileInfo(taxpayerFile);
myFileName = myFile.Name;
MessageBox.Show("Data Saved to " + myFileName);
}
You can try changing your code like this:
private void SaveToFile()
{
string taxpayerLine;
string taxpayerFile = string.Empty;
string myFileName;
FileInfo myFile;
using (SaveFileDialog taxpayerFileChooser = new SaveFileDialog())
{
taxpayerFileChooser.Filter = "All text files|*.txt";
if (DialogResult.OK == taxpayerFileChooser.ShowDialog())
{
taxpayerFile = taxpayerFileChooser.FileName;
}
}
if (!string.IsNullOrEmpty(taxpayerFile))
{
using (StreamWriter fileWriter = new StreamWriter(taxpayerFile, true))
{
foreach (Taxpayer tp in Taxpayers)
{
taxpayerLine = tp.Name + "," +
tp.Salary.ToString() + "," +
tp.InvestmentIncome.ToString() + "," +
(tp.InvestmentIncome + tp.Salary).ToString() + "," +
tp.GetRate().ToString() + "," +
tp.GetTax().ToString();
fileWriter.WriteLine(taxpayerLine);
}
}
myFile = new FileInfo(taxpayerFile);
myFileName = myFile.Name;
MessageBox.Show("Data Saved to " + myFileName);
}
else
{
MessageBox.Show("Data not saved");
}
}
The using statement explicit calls the Dispose() method of disposable objects after the block execution. http://msdn.microsoft.com/en-us/library/yh598w02.aspx
I am having a problem with creating a url link (shortcut) in a non-system folder. The link is getting created properly on the desktop without any problem, but if I change the path to a non-system folder the folder remains empty and there is no error message either. Is there a restriction on the paths allowed? Why is there no error message? Code is given below:
private void urlShortcutToFolder(string linkName, string linkUrl)
{
//string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
//using (StreamWriter writer = new StreamWriter(deskDir + "\\" + linkName + ".url"))
string nonSystemDir = "C\\Downloads";
using (StreamWriter writer = new StreamWriter(nonSystemDir + "\\" + linkName + ".url"))
{
writer.WriteLine("[InternetShortcut]");
writer.WriteLine("URL=" + linkUrl);
writer.Flush();
}
}
If you are running your application locally then your code is right. It must work.
if your application is running oline then you have to set permission for Internet user on the folder where you want to save your url.
Hope this will solve your problem
For as far I know this no proper path:
string nonSystemDir = "C\\Downloads";
Shouldn't it be
string nonSystemDir = "C:\\Downloads";
or more readable
string nonSystemDir = #"C:\Downloads";
You could also add System.IO.Directory.Exists like so
private void urlShortcutToFolder(string linkName, string linkUrl)
{
//string deskDir = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
//using (StreamWriter writer = new StreamWriter(deskDir + "\\" + linkName + ".url"))
string nonSystemDir = #"C:\Downloads";
if(!System.IO.Directory.Exists(nonSystemDir))
{
throw New Exception("Path " + nonSystemDir + " is not valid");
}
using (StreamWriter writer = new StreamWriter(nonSystemDir + "\\" + linkName + ".url"))
{
writer.WriteLine("[InternetShortcut]");
writer.WriteLine("URL=" + linkUrl);
writer.Flush();
}
}