I Need save the txt file on a correct create folder. But its saving on C:\Nova Pasta i need save on "C:\Nova pasta\"+valor.retorna_nome+comboBox1.Text whats is wrong ?
private void btn_SaveFile_Click(object sender, EventArgs e)
{
objSQL.Search_RGP_CadastroPrint(Convert.ToInt32(comboBox1.Text), str_list);
objSQL.SearchPrint(Convert.ToInt32(comboBox1.Text));
string path = #"C:\Nova pasta\"+valor.retorna_nome+comboBox1.Text;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
StreamWriter file = new System.IO.StreamWriter(path + ".txt");
file.WriteLine("---------------------------------------------------------------------------------------------------------");
file.WriteLine("Nome: " + valor.retorna_nome);
file.WriteLine("RGP: " + comboBox1.Text);
file.WriteLine("Endereço: " + valor.retorna_endereco);
file.WriteLine("Telefone: " + valor.retorna_telefone + " Celular: " + valor.retorna_celular + "\r\n");
str_list.ForEach(file.WriteLine);
file.Close();
}
Say valor.retorna_nome is "hello", and comboBox1.Text is "world". Your code does the following:
string path = #"C:\Nova pasta\"+valor.retorna_nome+comboBox1.Text;
// -> path = "C:\Nova pasta\helloworld"
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
// -> created directory "C:\Nova pasta\helloworld"
}
StreamWriter file = new System.IO.StreamWriter(path + ".txt");
// -> writes to file "C:\Nova pasta\helloworld.txt"
So it's doing exactly what you told it to. What would you like the directory to be called? And the filename?
Your String path is equals to something like that : "C:\Nova pasta\aNameXXX"
where :
aName = valor.retorna_nome
XXX = Combobox1.Text
You create a directory, this must success, but after that your file path is :
path+.txt : "C:\Nova pasta\aNameXXX.txt"
it's creating a file named (aNameXXX.txt) next to your folder.
you need to add an "\" and a name to your file to make a path like : "C:\Nova pasta\aNameXXX\FILENAME.txt"
StreamWriter file = new System.IO.StreamWriter(path + "\" + FILENAME + ".txt");
Related
I am trying to increment the filename (e.g., "file1.csv", "file2.csv", etc.), each time a new file is generated. I followed this thread Increment the file name if the file already exists in c# but the solution is not useful for my case. What I want to do is check if the file exists in the first place and if it does write in it. If it doesn't create one and write. The problem is that if the file exists but it's from another user, I want the system to increment the file number and not write to the same file just because it exists. What I have so far:
public void saveFile()
{
int count = 0;
string title = "TimeStamp,Name,Trial,Time_spent-dist,Time_spent_tar\n";
string output = System.DateTime.Now.ToString("mm_ss_ffff") + "," +
currentScene.name.ToString() + "," +
trialNum.ToString() + "," +
timerDistractor.ToString() + "," +
timerTarget.ToString();
string fname = "User_" + count + ".csv";
string path = Path.Combine(Application.persistentDataPath, fname);
if (File.Exists(path))
{
File.AppendAllText(path, "\n" + output);
}
else
{
StreamWriter writer = new StreamWriter(path);
writer.WriteLine(title + "\n" + output);
writer.Close();
}
}
Any pointers?
I'm using C# in Visual Studio 2017 Community.
I have a working, fully functional program that I am trying to optimize. In a nutshell, the program reads text and numbers from text files, does some math and reformatting, then outputs to a new text file.
The part I am trying to optimize is the way lines of text are written to the output file. Here is what works:
using System.IO
// Let's start building the MA output text file now.
// Designate an output file --- put it in same directory as original files
// give MA file ame name as the original file -- but different extension.
maOutFile = dir + "\\" + serialNumber[f] + ".ma";
//Create MA header lines and write to file.
string maHeaderLine1 = "TITLE: S/N:" + serialNumber[f] + "\n";
string maHeaderLine2 = "ENGLISH(IN)/METRIC(MM) INDICATOR :IN-P\n";
// Open up the file for writing
File.WriteAllText(maOutFile, maHeaderLine1);
File.AppendAllText(maOutFile, maHeaderLine2);
The above code works fine. My concern is that it's not very efficient, especially over a slow network. It opens and closes the file every time it writes to it.
So, to make this run faster, I thought I would try StreamWriter.
My StreamWriter code looks like this:
// Designate an output file --- put it in same directory as the original files
// give MA file same name as the original file -- with different extension.
// maOutFile = dir + "\\" + serialNumber[f] + ".ma";
StreamWriter outfile;
outfile = dir + "\\" + serialNumber[f] + ".ma";
//Create MA header lines and write to file.
string maHeaderLine1 = "TITLE: S/N:" + serialNumber[f] + "\n";
string maHeaderLine2 = "ENGLISH(IN)/METRIC(MM) INDICATOR :IN-P\n";
// Open up the file for writing
//File.WriteAllText(maOutFile, maHeaderLine1);
//File.AppendAllText(maOutFile, maHeaderLine2);
outfile.WriteLine(maHeaderLine1);
outfile.WriteLine(maHeaderLine2);
Visual Studio doesn't like my new code using StreamWriter. It puts a red line under everything to the right of the equals sign in the line "outfile = dir + "\" + serialNumber[f] + ".ma";
When I hover my mouse over the redlined code, the message is "cannot implicitly convert type string to System.IO.StreamWriter".
What doesn't it like about my new code?
You are assigning a string variable to a StreamWriter object instead of creating a StreamWriter object.
Try the following
using (StreamWriter sw = new StreamWriter(dir + "\\" + serialNumber[f] + ".ma"))
{
string maHeaderLine1 = "TITLE: S/N:" + serialNumber[f] + "\n";
string maHeaderLine2 = "ENGLISH(IN)/METRIC(MM) INDICATOR :IN-P\n";
// Open up the file for writing
//File.WriteAllText(maOutFile, maHeaderLine1);
sw.WriteLine(maHeaderLine1);
sw.WriteLine(maHeaderLine2);
}
You're trying to assign a string to a StreamWriter here:
outfile = dir + "\\" + serialNumber[f] + ".ma";
And looking at the code you're trying to open a file as a stream, something along the lines of:
string outFileDir = dir + "\\" + serialNumber[f] + ".ma";
StreamWriter outFile = new StreamWriter(outFileDir);
string fileName = dir + "\\" + serialNumber[f] + ".ma" ;
try
{
using (StreamWriter writer = new StreamWriter(fileName))
{
string maHeaderLine1 = "TITLE: S/N:" + serialNumber[f] + "\n";
string maHeaderLine2 = "ENGLISH(IN)/METRIC(MM) INDICATOR :IN-P\n";
writer.Write(maHeaderLine1 + maHeaderLine2);
}
}
catch(Exception exp)
{
Console.Write(exp.Message);
}
}
I'm trying to create an album and what I want to do, is to copy a picture from its original path to a specific folder and rename (the copy) right after.
Here is a piece of my code (note that "picturedir" is a path):
string PCname = Environment.UserName;
Image File;
OpenFileDialog openfile = new OpenFileDialog();
openfile.InitialDirectory = #"C:\Users\" + PCname + #"\Pictures";
if (openfile.ShowDialog() == DialogResult.OK)
{
try
{
File = Image.FromFile(openfile.FileName);
pictureBox3.Image = File;
pictureBox3.Image.Save(picturedir + "\\" + openfile.SafeFileName);
System.IO.File.Move(picturedir + "\\" + openfile.SafeFileName,
picturedir + "\\" + "1");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
As seen in the last line inside the "try", I want to rename the chosen picture, simply to "1". However, this last line gives an error "Cannot create a file when that file already exists". Any ideas?
P.S.: If I do not use the last "try" line: System.IO.File.Move(picturedir + "\\" + openfile.SafeFileName, picturedir + "\\" + "1"); it does copy the chosen picture but it obviously does not rename it at all.
Here is an article about work with files.
From article:
static void Main()
{
string fileName = "test.txt";
string sourcePath = #"C:\Users\Public\TestFolder";
string targetPath = #"C:\Users\Public\TestFolder\SubDir";
// Use Path class to manipulate file and directory paths.
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
// To copy a folder's contents to a new location:
// Create a new target folder, if necessary.
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
// To copy a file to another location and
// overwrite the destination file if it already exists.
System.IO.File.Copy(sourceFile, destFile, true);
}
If you use different file names, you get copy with new name.
I am trying to upload a file that is attached to a FileUpload control to a folder that is created in FTP. The Folder is getting created without issue but I can't seem to upload the file.
It seems as though my filepath to the source file is incorrect in the line String filePath = Server.MapPath("~" + #"\" + nameToGiveFolder); I have tried multiple variations of the file path but cannot seem to get the file uploaded.
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = FileUpload1.FileName;
string ftphost = WebConfigurationManager.AppSettings["myHost"].ToString();
string u = WebConfigurationManager.AppSettings["u"].ToString();
string p = WebConfigurationManager.AppSettings["p"].ToString();
string nameToGiveFolder = FileUpload1.FileName.ToString().Substring(0, FileUpload1.FileName.ToString().LastIndexOf("."));
string ftpfullpath = "ftp://" + ftphost + "/" + nameToGiveFolder;
FtpWebRequest ftp = (FtpWebRequest)FtpWebRequest.Create(ftpfullpath);
ftp.Method = WebRequestMethods.Ftp.MakeDirectory;
ftp.Credentials = new NetworkCredential(u, p);
FtpWebResponse CreateFolderResponse = (FtpWebResponse)ftp.GetResponse();
if (FileUpload1.HasFile)
{
try
{
Label1.Text = "Has File";
String filePath = Server.MapPath("~" + #"\" + nameToGiveFolder);
FileUpload1.SaveAs(filePath);
}
catch (Exception ex)
{
Label1.Text = ex.ToString();
}
}
else
{
Label1.Text = "No File";
}
}
Use Path.GetFileNameWithoutExtension(). to get the file name
FileUpload1.SaveAs(Server.MapPath(string.Format("~/{0}/{1}", Path.GetFileNameWithoutExtension(FileUpload1.FileName), FileUpload1.FileName)));
Note that you need to give the file name as well, if the file name is abc.jpg, above code try to create folder under your root of the web side called abc and save the file inside that folder with file name abc.jpg
i think your problem of line String filePath = Server.MapPath("~" + #"\" + nameToGiveFolder); is only having folder path at the end. when you call FileUpload1.SaveAs you need to have full file path.
Update
You get the error
System.IO.DirectoryNotFoundException: Could not find a part of the
path
because you don't have directory with the name of file name. I'm not where exactly you want to put the file. if you going to put the file in new directory, you need to create that directory first.
var folderpath = Server.MapPath(string.Format("~/{0}", Path.GetFileNameWithoutExtension(FileUpload1.FileName)));
System.IO.Directory.CreateDirectory(folderpath);
FileUpload1.SaveAs(Path.Combine(folderpath, FileUpload1.FileName));
I want to save my text file in a F drive but this file is written to a default folder of program . How to save it by guiding a path
string[] contents = new string[2];
contents[0] = "Name: " + textBox1.Text;
contents[1] = "age: " + textBox2.Text;
string path = #"F:\\"; // path to file
System.IO.File.WriteAllLines(textBox1.Text + ".txt", contents);
It would be a good idea to actually use your path variable:
string path = System.IO.Path.Combine(#"F:\", textBox1.Text + ".txt");
System.IO.File.WriteAllLines(path, contents);
Because you defining a path,but you don't use it.
string path = #"F:\" + textBox1.Text + ".txt";
File.WriteAllLines(path, contents);
As an alternative, you can use File.Move after you created it like;
File.WriteAllLines(textBox1.Text + ".txt", contents);
File.Move(Directory.GetCurrentDirectory() + textBox1.Text + ".txt",
path + textBox1.Text + ".txt");