I am working on a login system on WPF and C#, and im taking the Input out of a textbox and checking if the input (username or else) exists.
I do that with:
string selectedUser = User.Text;
if (File.Exists(#"" + path + selectedUser + ".txt"))
then i want to create a text file with the name of the user.
i do that with:
File.WriteAllLines(#"" + result + User + ".txt", User);
but it tells me that i cant convert a String to String[] (array).
And i searched the whole internet but couldnt find how to convert it, so i would love to hear a answer
from you guys.
The File.WriteAllLines method writes an array of string to a file.
public static void WriteAllLines (string path, string[] contents);
Creates a new file, writes one or more strings to the file, and then closes the file.
Instead, use the File.WriteAllText method.
public static void WriteAllText (string path, string contents);
Creates a new file, write the contents to the file, and then closes the file. If the target file already exists, it is overwritten.
Related
I don't know if it's possible, but i wanted to ask and get some help.
So i have an .txt file inside my solution, and i was wondering if it would be possible to move it to desktop by a button in my C# Program. Picture to Solution Item
So let's say i compiled my C# Project, i would want it to by a button press to move that .txt file to desktop that is inside my Program.
Like a VirtualBox that enigma has.
What i have tried is, but whenever i run program it just tries to find the .txt file externally, and not the one inside the program.
private void Button_Click(object sender, EventArgs e)
{
string sourcePath = Directory.GetParent(AppDomain.CurrentDomain.BaseDirectory).Parent.FullName;
string destinationPath = #"C:\";
string sourceFileName = "TextFile1.txt";
string destinationFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".xml"; // Don't mind this. I did this because I needed to name the copied files with respect to time.
string sourceFile = System.IO.Path.Combine(sourcePath, sourceFileName);
string destinationFile = System.IO.Path.Combine(destinationPath, destinationFileName);
if (!System.IO.Directory.Exists(destinationPath))
{
System.IO.Directory.CreateDirectory(destinationPath);
}
System.IO.File.Copy(sourceFile, destinationFile, true);
}
Returns
Picture of error
Best Regards.
In my Unity3D project I have several text fields. I saved my text in some text files.
When I test my project on the computer everything works fine, and my code reads the text files. But if I upload to my iPad it won't work and the text fields stay empty.
In the image you can see where I have saved my text files.
To read my text files I use the following code:
public Text infoText;
void Update()
{
readTextFile("FileName", "StepNumber")
}
public void readTextFile(string fileName, string stepNumber)
{
StreamReader txt_Reader = new StreamReader("Assets/Resources/Text_Files/" + fileName + ".txt");
while(!txt_Reader.EndOfStream)
{
string txt_String = txt_Reader.ReadLine();
if(txt_String.Contains(stepNumber))
{
string[] separator = { "_" };
string[] strList = txt_String.Split(separator, System.StringSplitOptions.RemoveEmptyEntries);
infoText.text = string.Join("\n", strList.Skip(1));
}
}
}
What do I have to change that my iPad can read from the text files?
EDIT:
My text files looks like this:
Step 1:
* Some Text
* Some Text
Step 2:
* Some Text
* Some Text
* Some Text
Step 3:
* Some Text
Step 4:
* Some Text
So each * should be a new line in my text field. With my old c# code this was no problem, but with
var lines = textFiles.text.Split(new char[] { `*` });
foreach(var line in lines)
{
...
}
i do not know how I can do that, that my text field shows all two lines for step one.
First of all from the Best Practices for the Resources folder
**Don't use it!
Please read the reasons there.
In general for system paths do never use simple string concatenation + "/" +!
Rather use Path.Combine which automatically uses the correct path separators according to the executing platform
Path.Combine(Application.dataPath, "Resources", "Text_Files", fileName + ".txt");
However, you don't/can't simply use a StreamReader to access the Resources folders (See Resources API since it is packed into the build so you have to go through Resources.Load like
// Here you can use / since this is how Unity stores internal paths
// for load you omit the suffix
TextAsset textFile = Resources.Load<TextAsset>("Text_Files/" + filename);
string fileContent = textFile.text;
Or also have a look at Resources.LoadAsync to not block the main thread meanwhile.
BUT
Speaking about blocking the main thread: What you definitely do not want to do is using any of these within Update thus doing heavy FileIO/Loading every frame!
Store the content of that file once as it won't change afterwards anyway!
Depending on your needs you could also simply put your file in any other folder inside the Assets and simply use a TextAsset field directly and drag it into according slot via the Inspector
public TextAsset textFile;
Finally you can then go through the lines one by one using e.g.
var lines = textFile.text.Split(new char[]{'/n'});
foreach(var line in lines)
{
...
}
Note that also that Split is a quite heavy operation since it has to parse every single character in the string and create new substrings so even store these results somewhere in a field of you need them multiple times during runtime!
Typed on smartphone but I hope the idea gets clear
In your case, StreamReader txt_Reader = new StreamReader("Assets/Resources/Text_Files/" + fileName + ".txt"); points to a file on your computer. Assets/Resources/Text_Files/ only exists on your computer.
You need to access a folder that exists on your iPad. It's likely you also didn't save your data to a folder existing on your IPad.
For other devices you could use : Application.persistentDataPath + "/" + fileName
Source: https://docs.unity3d.com/ScriptReference/Application-dataPath.html
if (File.Exists(#"C:\\Users" + Environment.UserName + "\\Desktop\\test"))
{ /\
this file has no file extension
}
The file test has no extension and I need help to either move or rename this file to something with a extension
Having no extension has no bearing on the function.
Also, a rename is really just a move "in disguise", so what you want to do is
File.Move(#"C:\Users\Username\Desktop\test", #"C:\Users\Username\Desktop\potato.txt")
Please bear in mind the # before the string, as you haven't escaped the backslashes.
There's nothing special about extensionless files. Your code is broken because you use string concatenation to build a path and you're mixing verbatim and regular string literal syntax. Use the proper framework method for this: Path.Combine().
string fullPath = Path.Combine(#"C:\Users", Environment.UserName, #"Desktop\test");
if(File.Exists(fullPath))
{
}
You also should use the proper framework method to get the desktop path for the current user, see How to get a path to the desktop for current user in C#?:
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string fullPath = Path.Combine(desktopPath, "test");
Then you can call File.Move() to rename the file, see Rename a file in C#:
if(File.Exists(fullPath))
{
string newPath = fullPath + ".txt";
File.Move(fullPath, newPath);
}
You can get all files without extension in this way:
var files = Directory.EnumerateFiles(#"C:\Users\Username\Desktop\")
.Where(fn => string.IsNullOrEmpty(Path.GetExtension(fn)));
Now you can loop them and change the extension:
foreach (string filePath in filPaths)
{
string fileWithNewExtension = Path.ChangeExtension(filePath, ".txt");
string newPath = Path.Combine(Path.GetDirectoryName(filePath), fileWithNewExtension);
File.Move(filePath, newPath);
}
As you can see, the Path-class is a great help.
Update: if you just want to change the extension of a single file that you already know it seems that Dasanko has already given the answer.
I have a method that i am using to replace values in a txt file.
protected void SendFormData(NameValueCollection formData)
{
string fileName = Server.MapPath("/_TextTemplate/textTemplate.txt");
string emailBody = File.ReadAllText(fileName);
foreach (string val in formData.AllKeys)
{
emailBody = emailBody.Replace("##"+ val +"##", formData[val]);
}
}
I plan on saving a copy of this text file after i have replaced the values. How can give this file a logical name and save a copy of it in my directory?
I did some googleing and File.WriteAllLines keeps popping up.
File.WriteAllLines(#"/_TextTemplate/" + formData[0] + ".txt", formData[0]);
But VS is complaining about that.
File.WriteAllLines
Expects an IEnumerable<string> as an argument. You want
File.WriteAllText(#"/_TextTemplate/" + formData[0] + ".txt", formData[0])
I'm working with asp.net project where user can upload files to server. I want to save the file with its original name, but if file with the same name already exists How can I generate a filename with a number in the parenthesis like windows does?
Files are uploaded to a particular folder and saved with its client side name itself. So, If a file named myimage.jpg is uploaded and a file with same name already exists in the server, I need to rename it to myimage(1).jpg or if 'myimage.jpg' to 'myimage(n).jpg' exists, I need to rename it to myimage(n+1).jpg.
What will be the best way to search for and generate such file names? My first guess was to use linq with regex over DirectoryInfo.EnumerateFiles(), but is that a good approach?
If the files with same orginal name don't have to be shown sorted by upload date/time, you could simply append System.Guid.NewGuid().ToString() to the file name.
public static object lockObject = new object();
void UploadFile(...)
{
//-- other code
lock (lockObject)
{
int i = 1;
string saveFileAs = "MyFile.txt";
while (File.Exists(saveFileAs))
{
string fileNameWithoutExt = Path.GetFileNameWithoutExtension(saveFileAs);
string ext = Path.GetExtension(saveFileAs)
saveFileAs = String.Concat(fileNameWithoutExt, "(", i.ToString(), ")", ext);
i++;
}
//-- Now you can save the file.
}
}
You don't need LINQ or regex.
If the original filename exists, append (1) to the name.
If that exists, append (2) to the (original) name.
And so on...