Reputation: 85
I'm trying to write to a file, in a specified area from the console line. (Like C:) The application crashes when I publish and run its .exe My code is:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
public static void Main(string[] args)
{
string arg1 = null;
if (args.Length > 0)
arg1 = args[0];
Console.WriteLine(arg1);
Console.WriteLine(args);
string tf = "\tf1.txt";
string tf1 = arg1 + tf;
Console.WriteLine(tf1);
System.Console.Title = "Data Adder (For the test)";
Random rnd = new Random();
int r1 = rnd.Next(0, 20);
byte[] bytes = new byte[255*r1];
var TF1 = new BinaryWriter(File.Open(@arg1+"tf1.txt",FileMode.Open));
TF1.Write(bytes);
TF1.Close();
Console.ReadKey();
}
private static int Random(int p1, int p2)
{
throw new NotImplementedException();
}
}
}
anyone know whats wrong? (Its in C#)
Upvotes: 0
Views: 174
Reputation: 43023
If you're passing just C:
from command line, you need to switch this line
var TF1 = new BinaryWriter(File.Open(@arg1+"tf1.txt",FileMode.Open));
to
var TF1 = new BinaryWriter(File.Open(arg1+@"\tf1.txt",FileMode.Open));
Or the path is invalid C:tf1.txt
Also, you should check if the file exists before opening it:
if (File.Exists(arg1 + @"\tf1.txt"))
{
var TF1 = new BinaryWriter(File.Open(arg1 + @"\tf1.txt", FileMode.Open));
TF1.Write(bytes);
TF1.Close();
}
Your full code is (with minimal changes):
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ConsoleApplication1
{
class Program
{
public static void Main(string[] args)
{
string arg1 = null;
if (args.Length > 0)
arg1 = args[0];
Console.WriteLine(arg1);
Console.WriteLine(args);
string tf = "\tf1.txt";
string tf1 = arg1 + tf;
Console.WriteLine(tf1);
System.Console.Title = "Data Adder (For the test)";
Random rnd = new Random();
int r1 = rnd.Next(0, 20);
byte[] bytes = new byte[255 * r1];
for (int i = 0; i < bytes.Length; i++)
bytes[i] = 65;
string filepath = Path.Combine(arg1, @"\tf1.txt");
if (File.Exists(filepath))
{
var TF1 = new BinaryWriter(File.Open(filepath, FileMode.Open));
TF1.Write(bytes);
TF1.Close();
}
Console.ReadKey();
}
private static int Random(int p1, int p2)
{
throw new NotImplementedException();
}
}
}
Upvotes: 0
Reputation: 71
Be careful when generating file paths. Use Path.Combine instead of string concatenation.
Upvotes: 1
Reputation: 18749
I can see you're using a backslash here....
string tf = "\tf1.txt";
but not here...
var TF1 = new BinaryWriter(File.Open(@arg1+"tf1.txt",FileMode.Open));
It's worth you stepping through the code and seeing what the values are.
Upvotes: 0