I'm making a basic program, and when it comes to saving data I'm trying to put it into a .txt - which is working just fine. Problem is, I can't save the seconds/hours in addition to the date, so my solution was to just get the date and then put 1, 2, 3 respectively on most recent files. The code I made was:
static string FileName()
{
string fileName = "";
char last = ' ';
int lastDigit = 0;
string lastDigitString = "";
string directory = Directory.GetCurrentDirectory();
if (File.Exists(DateTime.Now.Date.ToString("dd-MM-yy" + "1") + ".txt"))
{
fileName = Path.GetFileNameWithoutExtension(newFileName + ".txt");
last = fileName[fileName.Length - 1];
lastDigit = int.Parse(last.ToString());
lastDigit = lastDigit + 1;
lastDigitString = lastDigit.ToString();
newFileName = fileName + lastDigitString;
}
else
{
newFileName = DateTime.Now.Date.ToString("dd-MM-yy" + "1");
}
return fileName;
}
with newFileName being defined as a global variable at the top.
public static string newFileName = DateTime.Now.Date.ToString("dd-MM-yy" + "1");
I've been messing around with some things might be out of place. My solution was to get the filename and then take off the .txt - which would then leave me with just the name where I get the last digit of the name and then increase it by one, then add it to the end of a new file name. It goes 'FileName1' then 'FileName12' which is what I hoped to get, but once there it just keeps adding to 'FileName12' which is obviously from the appending set to true, but I hoped for a 'FileName123'.
Is there a requirement not to use the Hour/Minute/Second for your file name?
You are using DateTime.Now.Date.ToString(..), which will strip out the hour/minute/second data. You can use DateTime.Now.ToString(..) to reserve the sub-day data.
You'll need to provide your own format string to generate a file-name-friendly output.
This is because time has colon : and it is not supported as windows file
Related
Console.WriteLine("What name would you like to be known as?");
string usernameforscore = Console.ReadLine();
int classicscore = 0;
string path = "";
File.AppendAllText(path, (usernameforscore + " " + classicscore + Environment.NewLine));
So essentially this will write a name and a score to a file one line after another, I want to add some kind of validation that checks if someone's entered username is in the file, it will then override that entire line with the new username and score data.
"classicsscore" references the score of the user, stored as an integer previously. It is then placed into a text file along with the person's inputting string username i.e. "John 12". What I want is that if a person inputs John as their username, which the score 400, the line would then be replaced with "John 400" and not affect the rest of the text file.
I'm using Visual studio, C# console program.
Apologies if this is a duplicate, couldn't find a specific answer myself.
Im thinking something like this should work for you.
public void AddOrUpdate(string userName, int score)
{
string path = "";
var newLine = userName + " " + score;
var lines = File.ReadAllLines(path);
var wasUpdated = false;
using (var writer = new StreamWriter(path))
{
foreach (var line in lines)
{
var foundUserName = line.Substring(0, line.LastIndexOf(' '));
if (foundUserName == userName)
{
writer.WriteLine(newLine);
wasUpdated = true;
}
else
writer.WriteLine(line);
}
if(!wasUpdated)
writer.WriteLine(newLine);
}
}
But unless you need this specific format for some reason using a database would be a much better option.
So I have grown tired of having to use the import wizard to create a table from a new TXT tab delimited file every time I get a new text file i have to analyze. Most of what I am doing is rough data analysis, but I grow tired of access SQL and the documents sometimes are large enough that Excel analysis wont cut it. I haven't found a great way to import Data from multiple files into SQL Server quickly. I know of bulk import, but from my understanding you need a table already made to use it. My text files are ALWAYS different so i cant just create a generic table and recreate it.
I am writing a C# code that hopefully eventually will take a filepath and take a copy of every text file in the path and cut it down to the first {CR}{LF} in each doc, define my delimiter '\t' ',' '|' etc. , and make a create table statement for every file in the path. I want to do this so I can then do a simple bulk import for each file and be done.
This is what I have so far: Im trying to get it to work on a SINGLE tab delimited file
private void button4_Click(object sender, EventArgs e)
{
string pathOfFile = textBox2.Text;
string origFileText = File.ReadAllText(pathOfFile);
int intIndexofCRLF = origFileText.IndexOf(Environment.NewLine);
string strIndexfCRLF = intIndexofCRLF.ToString();
string strJustHeader = origFileText.Substring(0, intIndexofCRLF);
string[] splitarray = strJustHeader.Split('\t');
string tablename = textBox3.Text;
string SQLPart1 = "CREATE TABLE " + tablename + "( ";
string sqlbody = "";
for (int i = 0; i < splitarray.Length; i++)
{
sqlbody = sqlbody + "[" + splitarray[i] + "] " + "varchar(255), " ;
}
string SQLpart2 = sqlbody.Substring(0, sqlbody.Length - 1);
string SQLPart3 = ");"
MessageBox.Show(SQLPart1 + SQLPart2 + SQLPart3);
}
For some reason, my array is messing up when I do this.
My input is D:\newtext.txt
abd abc ans azd
1 2 3 4
My desired output is
CREATE TABLE newtext ( abd varchar(255), abc varchar(255), ans varchar(255), azd varchar(255));
Thanks for the help!
I would improve few things in this code :
StringBuilders are more efficient than just concatenating strings,
you should use them
Handing both windows ("\r\n") and Unix ("\n") lines ends.
Reading only the first line of the file from disk instead of reading all of
the file to the memory and then get the first line from it
Here an example code that contains those improvements :
string tableName = "myTable";
string delimeter = " ";
string line = null;
using (Stream stream = File.OpenRead("FilePath"))
using (StreamReader sr = new StreamReader(stream))
{
line = sr.ReadLine();
}
string fileHeader = line.Replace("\r", string.Empty).Replace("\n", string.Empty);
string[] fileHeaderSegments = fileHeader.Split(new string[] { delimeter }, StringSplitOptions.None);
StringBuilder sb = new StringBuilder(string.Format("CREATE TABLE {0} (", tableName));
for (int i = 0; i < fileHeaderSegments.Length; i++)
{
if (i != 0)
{
sb.Append(",");
}
sb.Append(fileHeaderSegments[i]);
sb.Append(" varchar(255)");
}
sb.Append(");");
Console.WriteLine(sb.ToString());
Console.ReadKey();
I have a string called fileNameArrayEdited which contains "\\windows".The below if statement is not running.
Thinking the problem is else where as people have given me code that should work will be back once I found the problem... thanks!
if (fileNameArrayEdited.StartsWith("\\"))
{
specifiedDirCount = specifiedDirCount + 1;
}
// Put all file names in root directory into array.
string[] fileNameArray = Directory.GetFiles(#specifiedDir);
int specifiedDirCount = specifiedDir.Count();
string fileNameArrayEdited = specifiedDir.Remove(0, specifiedDirCount);
Console.WriteLine(specifiedDir.Remove(0, specifiedDirCount));
if (fileNameArrayEdited.StartsWith(#"\\"))
{
specifiedDirCount = specifiedDirCount + 1;
Console.ReadLine();
Use '#' at the beginning of your string if you are searching for exactly two slash
if (fileNameArrayEdited.StartsWith(#"\\"))
{
specifiedDirCount = specifiedDirCount + 1;
}
They are called verbatim strings and they are ignoring escape characters.For better explanation you can take a look at here: http://msdn.microsoft.com/en-us/library/362314fe.aspx
But I suspect in here your one slash is escape character
"\\windows"
So you must search for one slash like this:
if (fileNameArrayEdited.StartsWith(#"\"))
{
specifiedDirCount = specifiedDirCount + 1;
}
When we write
string s1 = "\\" ;
// actual value stored in s1 is "\"
string s2 = #"\\" ;
// actual value stored in s2 is "\\"
The second type of string(s) are called "verbatim" strings.
Getting this error The given path's format is not supported. at this line
System.IO.Directory.CreateDirectory(visit_Path);
Where I am doing mistake in below code
void Create_VisitDateFolder()
{
this.pid = Convert.ToInt32(db.GetPatientID(cmbPatientName.SelectedItem.ToString()));
String strpath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
String path = strpath + "\\Patients\\Patient_" + pid + "\\";
string visitdate = db.GetPatient_visitDate(pid);
this.visitNo = db.GetPatientID_visitNo(pid);
string visit_Path = path +"visit_" + visitNo + "_" + visitdate+"\\";
bool IsVisitExist = System.IO.Directory.Exists(path);
bool IsVisitPath=System.IO.Directory.Exists(visit_Path);
if (!IsVisitExist)
{
System.IO.Directory.CreateDirectory(path);
}
if (!IsVisitPath)
{
System.IO.Directory.CreateDirectory(visit_Path);\\error here
}
}
getting this value for visit_Path
C:\Users\Monika\Documents\Visual Studio 2010\Projects\SonoRepo\SonoRepo\bin\Debug\Patients\Patient_16\visit_4_16-10-2013 00:00:00\
You can not have : in directory name, I suggest you to use this to string to get date in directory name:
DateTime.Now.ToString("yyyy-MM-dd hh_mm_ss");
it will create timestamp like:
2013-10-17 05_41_05
additional note:
use Path.Combine to make full path, like:
var path = Path.Combine(strpath , "Patients", "Patient_" + pid);
and last
string suffix = "visit_"+visitNo+"_" + visitdate;
var visit_Path = Path.Combine(path, suffix);
In general always use Path.Combine to create paths:
String strPath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
String path = Path.Combine(strPath,"Patients","Patient_" + pid);
string visitdate = db.GetPatient_visitDate(pid);
this.visitNo = db.GetPatientID_visitNo(pid);
string fileName = string.Format("visit_{0}_{1}", visitNo, visitdate);
string visit_Path = Path.Combine(path, fileName);
bool IsVisitExist = System.IO.Directory.Exists(path);
bool IsVisitPath=System.IO.Directory.Exists(visit_Path);
To replace invalid characters from a filename you could use this loop:
string invalidChars = new string(Path.GetInvalidFileNameChars()) + new string(Path.GetInvalidPathChars());
foreach (char c in invalidChars)
{
visit_Path = visit_Path.Replace(c.ToString(), ""); // or with "."
}
You can't have colons : in file paths
You can't use colons (:) in a path. You can for example Replace() them with dots (.).
Just wanted to add my two cents.
I assigned the path from a text box to string and also adding additional strings, but I forgot to add the .Text to the text box variable.
So instead of
strFinalPath = TextBox1.Text + strIntermediatePath + strFilename
I wrote
strFinalPath = TextBox1 + strIntermediatePath + strFilename
So the path became invalid because it contained invalid characters.
I was surprised that c# instead of rejecting the assignment because of type mismatch, assigned invalid value to the final string.
So look at the path assignment string closely.
Here is what I have tried, please note that lblImageAlt.Text property has been set to 'Images/'
string ImgPath1 = lblImageAlt1.Text.ToString();
string ImgPath2 = lblImageAlt2.Text.ToString();
string ImgPath3 = lblImageAlt3.Text.ToString();
string filename1 = "";
string filename2 = "";
string filename3 = "";
if (fileuploadimages1.HasFile)
{
if (File.Exists(Server.MapPath(ImgPath1 + filename1)))
{
string extension = Path.GetExtension(filename1);
string name = Path.GetFileNameWithoutExtension(filename1);
int fileMatchCount = 1;
while (File.Exists(Server.MapPath(ImgPath1 + name + "(" + fileMatchCount + ")" + extension)))
fileMatchCount++;
fileuploadimages1.SaveAs(Server.MapPath(ImgPath1 + name + "(" + fileMatchCount + ")" + extension));
}
else
{
fileuploadimages1.SaveAs(Server.MapPath(ImgPath1 + filename1));
}
}
else
{
filename1 = "noImage.jpg";
}
but the same image does not get a number appended to it. What am I doing wrong here?
Path.GetFileName returns the whole filename with the extension.
Thus your code is checking if a file exists with a name like this:
image.jpg1
You should change the code to split the filename in two parts, the base filename and the extension, then check if the filename exists and then rebuild the filename from its parts adding the increment number until you find a non existant filename
// Extract just the filename from the posted file removing the path part (image.jpg)
filename1 = Path.GetFileName(fileuploadimages1.PostedFile.FileName);
baseFile = Path.GetFileNameWithoutExtension(fileuploadimages1.PostedFile.FileName);
extension = Path.GetExtension(fileuploadimages1.PostedFile.FileName);
int fileMatchCount = 1;
// Check if a file with the given name exists in the Images1 subfolder of the root folder of your site
while(File.Exists(Server.MapPath(Path.Combine(ImgPath1, filename1)))
{
// The given file exists already, so we now need to build
// a different (but related) filename using a counter....
// This will create a filename like 'image(001).jpg'
// and then we will restart the loop
fileName1 = string.Format("{0}({1:D3}){2}", baseFile, fileMatchCount, extension);
// ... but first increment the counter in case even the new name exists
fileMatchCount++;
}
// We exit the loop with a name that should not exists in the destination folder
fileuploadimages1.SaveAs(Server.MapPath(Path.Combine(ImgPath1, filename1));
You're not actually modifying filename1. You're checking if it ends in a (0), (1), etc. and incrementing your index, but never actually modifying the variable.
Try using
if(File.Exists(Server.MapPath(ImgPath1 + filename1)))
{
string extension = Path.GetExtension(filename1);
string name = Path.GetFileNameWithoutExtension(filename1);
int fileMatchCount = 1;
while(File.Exists(Server.MapPath(ImgPath1 + name + "(" + fileMatchCount + ")" + extension)))
fileMatchCount++;
fileuploadimages1.SaveAs(Server.MapPath(ImgPath1 + name + "(" + fileMatchCount + ")" + extension));
}
else
fileuploadimages1.SaveAs(Server.MapPath(ImgPath1 + filename1));