Increment file name by 1 if the file exists in c# - c#

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?

Related

C# ASP.Net: Read & Rewrite File based on session variables

I am working on a website ATM school project, and I need to be able to rewrite the account balance in the original .txt file based on session transactions. The .txt file contains 3 lines, each with (username),(password),(balance). The issue I'm having is that the program cannot write to file while it is still reading it. The loop works fine if I write to a different file, but I have to edit the original (so the updated balance is retained the next time the program is run). Below is the code from the Logout page load event.
//Stream variable
StreamReader readFile;
StreamWriter writeFile;
//Counter variable
int index = 0;
//Open file
readFile = File.OpenText(#"C:\C#\Project4_TSullivan\loginFile.txt");
//Array rows
const int ROWS = 3;
while (index < ROWS && !readFile.EndOfStream)
{
string str = readFile.ReadLine();
string[] tokens = str.Split(',');
//Check if username matches session username
if (tokens[0] == Convert.ToString(Session["sessionUserName"]))
{
//Update balance
tokens[2] = Convert.ToString(Session["sessionBalance"]);
}
if (index == 0)
{
writeFile = File.CreateText(#"C:\C#\Project4_TSullivan\loginFile.txt");
writeFile.WriteLine(tokens[0] + "," + tokens[1] + "," + tokens[2]);
writeFile.Close();
}
else
{
writeFile = File.AppendText(#"C:\C#\Project4_TSullivan\loginFile.txt");
writeFile.WriteLine(tokens[0] + "," + tokens[1] + "," + tokens[2]);
writeFile.Close();
}
index++;
}
//Close file
readFile.Close();
Please let me know if any additional info would be helpful. I may be going about this in entirely the wrong way, and any advice would be much appreciated. Thanks!
Edited
Here is the solution in case the mods want to save it. Using File.ReadAllLines I was able to store the contents of the file in an array. Then I created 3 more arrays (1 for each line in the file) to tokenize each line.
string path = #"C:\C#\Project4_TSullivan\loginFile.txt";
string[] readFile = File.ReadAllLines(path);
string[] token0 = readFile[0].Split(',');
string[] token1 = readFile[1].Split(',');
string[] token2 = readFile[2].Split(',');
if (token0[0] == Convert.ToString(Session["sessionUsername"]))
{
token0[2] = Convert.ToString(Session["sessionBalance"]);
}
else if (token1[0] == Convert.ToString(Session["sessionUsername"]))
{
token1[2] = Convert.ToString(Session["sessionBalance"]);
}
else
{
token2[2] = Convert.ToString(Session["sessionBalance"]);
}
using (StreamWriter writeFile = File.CreateText(path))
{
writeFile.WriteLine(token0[0] + "," + token0[1] + "," + token0[2]);
writeFile.WriteLine(token1[0] + "," + token1[1] + "," + token1[2]);
writeFile.WriteLine(token2[0] + "," + token2[1] + "," + token2[2]);
}

How to fix StreamWriter error "cannot implicitly convert type string to System.IO.StreamWriter"

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);
}
}

Value of a variable is not updating

I am currently working on a project that sweeps a mailbox for attachments and when one is found it is placed in the user's directory. My problem is that when I check if the file exist in the path, I alter the attachment's name and add a counter and time stamp, that way it is not over written. However, when it goes into the condition and changes the file name it never updates the path variable to include the right value of the Clean name variable.
string timeProcessed = DateTime.Now.ToString();
byte[] bytefiles = attachment.ContentBytes;
string cleanName = MakeCleanName(userEmail.Subject, attachment.Name);
string path = employeeStarPath + "\\" + cleanName;
// updated this in order to prevent images with the same name from overwritting eachother.
if (File.Exists(path))
{
cleanName = Path.GetFileNameWithoutExtension(attachment.Name).ToString()+"(" + counter + ")" + "-(Recieved - " + timeProcessed.Replace(":",".").Replace("/",".") + " )"+ Path.GetExtension(attachment.Name); << this value is not updated in the path variable.
}
Now I am aware I can update the path var by calling path = employeeStarPath + "\\" + cleanName; again but I feel that this makes my code a bit confusing.
I might not understood your question but can you just call the line "string path = employeeStarPath + "\" + cleanName;" at the end instead before the if?
string timeProcessed = DateTime.Now.ToString();
byte[] bytefiles = attachment.ContentBytes;
string cleanName = MakeCleanName(userEmail.Subject, attachment.Name);
// updated this in order to prevent images with the same name from overwritting eachother.
if (File.Exists(path))
{
cleanName = Path.GetFileNameWithoutExtension(attachment.Name).ToString()+"(" + counter + ")" + "-(Recieved - " + timeProcessed.Replace(":",".").Replace("/",".") + " )"+ Path.GetExtension(attachment.Name); << this value is not updated in the path variable.
}
string path = employeeStarPath + "\\" + cleanName;

Add column to Excel

using (System.IO.StreamWriter writer = new System.IO.StreamWriter(#"" + textBox2.Text + #"\" + filename.TrimStart() + ".csv", true))
{
if (!exists)
{
writer.WriteLine(DateTime.Now.ToLongDateString());
writer.WriteLine("REG.,BR.,BR.NAME,AC TYPE,PRODUCT,NO.OF ACS,ORG.CURRENCY BALANCE,ORG CURRENCY,BALANCE LKR");
writer.WriteLine(text.Replace("|", ","));
}
writer.WriteLine(text.Replace("|", ","));
////true is append parameter. I use this code to create Excel files. I want add new column and fill each cell with auto increment numbers.
As you didn't include the appropriate infos I take it that text includes all lines that you want to use and , is being used as the separator instead of the more commonly used ; .
The following splits this complete text into multiple lines and creates an "autoincrement" number that is appended as the last column.
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(#"" + textBox2.Text + #"\" + filename.TrimStart() + ".csv", true))
{
if (!exists)
{
writer.WriteLine(DateTime.Now.ToLongDateString());
writer.WriteLine("REG.,BR.,BR.NAME,AC TYPE,PRODUCT,NO.OF ACS,ORG.CURRENCY BALANCE,ORG CURRENCY,BALANCE LKR");
}
var textArray = text.Replace("|", ",").split(Environment.NewLine);
int number = 0;
foreach (string text in textArray)
{
number ++;
write.WriteLine(text + "," + number.ToString());
}

How to save data from form in a specific drive

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");

Categories