This question already has an answer here:
File.AppendText attempting to write to wrong location
(1 answer)
Closed 3 years ago.
I'm trying to edit a conf file by using line.Replace and write.WriteLine.
Debugging through the code, the line successfully changes.
Original string:
Changed string:
Somehow after the writer.WriteLine, the text still does not change. Below is my full code:
public void ChangeFileContent()
{
string textLoc = installPath + "\\DB\\influxdb-1.7.7-1\\influxdb.conf";
string[] arr = File.ReadAllLines(textLoc);
for (int i = 0; i < arr.Length; i++)
{
var writer = new StreamWriter(Path.GetFileName(textLoc));
string line = arr[i];
string output = line;
if (line.Contains("influxdb-1.7.7-1") == true)
{
output = line.Replace("D:", "C:");
}
writer.WriteLine(output);
writer.Close();
}
}
You could build all content and write it with File.WriteAllText or File.WriteAllLines.
Something like the following.
string textLoc = installPath + "\\DB\\influxdb-1.7.7-1\\influxdb.conf";
var lines = File.ReadAllLines(textLoc);
var newLines = lines.Select(line =>
line.Contains("influxdb-1.7.7-1")
? output = line.Replace("D:", "C:")
: line);
File.WriteAllLines(textLoc,newLines);
Related
This question already has answers here:
Copy files from Resources/StreamingAssets to Application.persistentDataPath upon installation
(2 answers)
Closed 4 years ago.
So, I'm developing Visual Novel in unity. The application is running smoothly in the pc but now I want it to run in android but the contents in my .txt file is not showing in screen. I assume that the error is that the text file in StreamingAssets folder couldn't be loaded and I don't know why. Here's my code:
void Start () {
path = "jar:file://" + Application.dataPath + "!/assets/StreamingAssets/Dialogue0.txt";
lines = new List<DialogueLine>();
Example();
}
IEnumerator Example()
{
if (path.Contains("://"))
{
var www = new WWW(path);
yield return www;
if (!string.IsNullOrEmpty(www.error))
{
Debug.LogError("Can't read");
}
LoadDialogue(www.text);
}
else
LoadDialogue(path);
}
void LoadDialogue(string filename)
{
string line;
StreamReader r = new StreamReader(filename);
using (r)
{
do
{
line = r.ReadLine();
if (line != null)
{
string[] lineData = line.Split('|');
if (lineData[0] == "Player")
{
DialogueLine lineEntry = new DialogueLine(lineData[0], "", 0, 0, "");
lineEntry.options = new string[lineData.Length - 1];
for (int i = 1; i < lineData.Length; i++)
{
lineEntry.options[i - 1] = lineData[i];
}
lines.Add(lineEntry);
}
else
{
DialogueLine lineEntry = new DialogueLine(lineData[0], lineData[1], int.Parse(lineData[2]), int.Parse(lineData[3]), lineData[4]);
lines.Add(lineEntry);
}
}
}
while (line != null);
r.Close();
}
}
Path of my .txt file
Contents of my .txt file
Just serialize your file to Appliction.persistentDataPath + filename and then read easly from it .It will save file in Windows(AppData/LocalLow/InYourUnityProject) in android (under company name folder)
Ok so i am making a tool for a special need.
There will be .mif files which i can open as a text file and read the content.
Using something simple like
DialogResult openFile = form.openFileDialog1.ShowDialog();
if (openFile == DialogResult.OK)
{
int size = -1;
try
{
//Add commas here
}
catch (IOException)
{
}
}
Now how do i add a comma at the end of each line in a file?
e.g something like this
319621.99946835 110837.002493295
319640.501385461 110850.59860145
319695.199120806 110879.700271183
to something like this (notice the commas at the end of each line)
319621.99946835 110837.002493295,
319640.501385461 110850.59860145,
319695.199120806 110879.700271183,
Now the pattern is different for this and it occurs 1000s of time in one file
Any ideas?
string sFilePath = "Insert.File.Path.Here";
File.WriteAllLines(sFilePath, File.ReadAllLines(sFilePath).Select(x => string.Format("{0},",x)));
How to read a file line by line you will find in this post.
at each line do simply:
CurrentLine = CurrentLine + ",";
If your text file isn't big, you can try this:
var path = "myfile.txt";
var lines = File.ReadAllLines (path);
var newContent = string.Join (",\r\n", lines);
File.WriteAllText (path, newContent);
It will not add comma to last line.
Use the methods of the File class:
public static string[] ReadAllLines(
string path
)
public static void WriteAllLines(
string path,
string[] contents
)
Like this
string[] lines = File.ReadAllLines(openFile.FileName);
for (int i = 0; i < lines.Length; i++) {
lines[i] += ",";
}
File.WriteAllLines(openFile.FileName, lines);
I'm back at it again with another question, this time with regards to editing text files. My home work is as follow
Write a program that reads the contents of a text file and inserts the line numbers at the beginning of each line, then rewrites the file contents.
This is what I have so far, though I am not so sure if this is the most efficient way of doing it. I've only started learning on handling text files at the moment.
static void Main(string[] args)
{
string fileName = #"C:\Users\Nate\Documents\Visual Studio 2015\Projects\Chapter 15\Chapter 15 Question 3\Chapter 15 Question 3\TextFile1.txt";
StreamReader reader = new StreamReader(fileName);
int lineCounter = 0;
List<string> list = new List<string>();
using (reader)
{
string line = reader.ReadLine();
while (line != null)
{
list.Add("line " + (lineCounter + 1) + ": " + line);
line = reader.ReadLine();
lineCounter++;
}
}
StreamWriter writer = new StreamWriter(fileName);
using (writer)
{
foreach (string line in list)
{
writer.WriteLine(line);
}
}
}
your help would be appreciated!
thanks once again. :]
this should be enough (in case the file is relatively small):
using System.IO;
(...)
static void Main(string[] args)
{
string fileName = #"C:\Users\Nate\Documents\Visual Studio 2015\Projects\Chapter 15\Chapter 15 Question 3\Chapter 15 Question 3\TextFile1.txt";
string[] lines = File.ReadAllLines(fileName);
for (int i = 0; i< lines.Length; i++)
{
lines[i] = string.Format("{0} {1}", i + 1, lines[i]);
}
File.WriteAllLines(fileName, lines);
}
I suggest using Linq, use File.ReadLinesto read the content.
// Read all lines and apply format
var formatteLines = File
.ReadLines("filepath") // read lines
.Select((line, i) => string.Format("line {0} :{1} ", line, i+1)); // format each line.
// write formatted lines to either to the new file or override previous file.
File.WriteAllLines("outputfilepath", formatteLines);
Just one loop here. I think it will be efficient.
class Program
{
public static void Main()
{
string path = Directory.GetCurrentDirectory() + #"\MyText.txt";
StreamReader sr1 = File.OpenText(path);
string s = "";
int counter = 1;
StringBuilder sb = new StringBuilder();
while ((s = sr1.ReadLine()) != null)
{
var lineOutput = counter++ + " " + s;
Console.WriteLine(lineOutput);
sb.Append(lineOutput);
}
sr1.Close();
Console.WriteLine();
StreamWriter sw1 = File.AppendText(path);
sw1.Write(sb);
sw1.Close();
}
I am using this code to write to a text file:
int num;
StreamWriter writer2;
bool flag = true;
string str = "";
if (flag == File.Exists(this.location))
{
File.WriteAllText(this.location, string.Empty);
new FileInfo(this.location).Open(FileMode.Truncate).Close();
using (writer2 = this.SW = File.AppendText(this.location))
{
this.SW.WriteLine("Count=" + this.Count);
for (num = 0; num < this.Count; num++)
{
this.SW.WriteLine(this.Items[num]);
}
this.SW.Close();
}
}
but I keep Getting System.IOException saying that the process cannot access the file because it is being used by another process at this code:
File.WriteAllText(this.location, string.Empty);
However, I check the text file and I find that it was updated.
You should be able to replace all of your code with the following if Items is an enumerable of string.
if (File.Exists(this.location))
File.WriteAllLines(this.location, this.Items);
If it isn't and you are harnessing ToString() from each object in Items you can do this:
if (File.Exists(this.location))
{
var textLines = Items.Select(x => x.ToString());
File.WriteAllLines(this.location, textLines);
}
This should fix your issue with the file being locked because it is only accessing the file one time where your original code is opening it 3 times.
EDIT: Just noticed your addition of adding a "Count" line. Here's a cleaner version using a stream.
if (File.Exists(this.location))
{
using (var fileInfo = new FileInfo(this.location)
{
using(var writer = fileInfo.CreateText())
{
writer.WriteLine("Count=" + Items.Count);
foreach(var item in Items)
writer.WriteLine(item);
}
}
}
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have txt file which contains number that I want to grab. This number has prefix which can be used to identify location inside file.
GeneratedNumber="120"
Number can be of any Int32 length value.
p.s. format of the file is .txt, one line contains more this key value pairs for example:
<Output Change="12.13" GeneratedNumber="120" Total="99.21" />
You can use the following code. Not very elegant or the best but tested and works fine.
string[] lines = File.ReadAllLines(Path.Combine(Application.StartupPath, "test.txt"));
foreach (string s in lines)
{
if (s.ToLowerInvariant().Contains("generatednumber"))
{
string temp = s.Substring(s.ToLowerInvariant().IndexOf("generatednumber"));
temp = temp.Substring(temp.IndexOf("\"") + 1);
temp = temp.Substring(0,temp.IndexOf("\""));
int yournumber;
if (int.TryParse(temp, out yournumber))
{
Console.WriteLine("Generated Number = ", yournumber);
}
}
}
I've only tested this as far as the xml side but this should work (You may wish to add error handling and the conversion to integers)
var values = new List<string>();
using(var sr = new StreamReader(fileName))
{
string line;
XmlDocument x = new XmlDocument();
while((line = sr.ReadLine()) != null)
{
x.LoadXml(line);
foreach(var node in x.GetElementsByTagName("Output"))
values.Add(node.Attributes["GeneratedNumber"].Value);
}
}
Tested using:
XmlDocument x = new XmlDocument();
x.LoadXml("<Output Change=\"12.13\" GeneratedNumber=\"120\" Total=\"99.21\" />");
Console.WriteLine(x.GetElementsByTagName("Output")[0]
.Attributes["GeneratedNumber"].Value);
Console.ReadLine();
you can use this code
// Read each line of the file into a string array. Each element
// of the array is one line of the file.
string[] lines = System.IO.File.ReadAllLines(#"C:\yourFile.txt");
foreach (string line in lines)
{
string sub = line.Substring(line.IndexOf("GeneratedNumber=") + 1);
int num = int.Parse(sub.IndexOf("\""));
// whatever you want to do with the integer
}
to read the text file lines and parse the lines after the "=" sign to integers.
depend on the look of the file you might use XmlDocument. please read about Xml here
string filePath = "your_file_path";
var match = System.Text.RegularExpressions.Regex.Match(
System.IO.File.ReadAllText(filePath),
#"GeneratedNumber=""(\d+)""",
System.Text.RegularExpressions.RegexOptions.IgnoreCase);
int num = match.Success ? int.Parse(match.Groups[1].Value) : 0;
Assuming there's only one instance of that number in the file or you want to grab only the first one even if there are multiple.
string[] lines = File.ReadAllLines("path to file");
Hashtable values = new Hashtable();
foreach (string line in lines)
{
if (line.Contains("=\""))
{
string[] split = line.Split('=');
values.Add(split[0], split[1].Replace("\"",""));
}
}
// GeneratedNumber is the value of GeneratedNumber in the file.
int GeneratedNumber = Int32.Parse(values["GeneratedNumber"].ToString());
This code should match your needs:
private static int GetNumber(string fileName)
{
string line;
string key = "GeneratedNumber=\"";
using (StreamReader file = new StreamReader(fileName))
{
while ((line = file.ReadLine()) != null)
{
if (line.Contains(key))
{
int startIndex = line.IndexOf(key) + key.Length;
int endIndex = line.IndexOf("\"", startIndex);
return int.Parse(line.Substring(startIndex, endIndex - startIndex));
}
}
}
return 0;
}
Also you may be interested in these articles:
Using of StreamReader
String methods
Int32.Parse method