I am new at programming and I'm really confused about how should I do this, because at first I thought I should ask user which path to export. However I have been told that I should check if it exists the directory and if doesn't I should create it. How can I even create a directory path or ask user if it can be created? Sorry if my question is too odd but I'm very confused about this, I was convinced that simply asking was enough to export data.
static void exportData(string[,] matrix)
{
var dir = "";
do
{
Console.Clear();
Console.Write("Insert path to export txt: ");
dir = Console.ReadLine();
} while (String.IsNullOrEmpty(dir));
var path = Path.Combine(dir, "export.txt");
using (StreamWriter sw = File.CreateText(path))
{
for (int i = 0; i < matrix.GetLength(0); i++)
{
for (int j = 0; j < matrix.GetLength(1) - 1; j++)
{
{
sw.Write($"\t{matrix[i, j]}\t");
}
}
Console.WriteLine("\n");
}
}
-
5\$\begingroup\$ This application seems to be very simple. Could you post all of its code? You should also explain what the format of the text file is and what is the purpose of it. \$\endgroup\$t3chb0t– t3chb0t2018年08月21日 11:16:12 +00:00Commented Aug 21, 2018 at 11:16
-
\$\begingroup\$ @t3chb0t - what's the relevance of it being 'simple'? \$\endgroup\$JᴀʏMᴇᴇ– JᴀʏMᴇᴇ2018年08月21日 13:56:38 +00:00Commented Aug 21, 2018 at 13:56
-
\$\begingroup\$ Can you use json serialization? \$\endgroup\$IEatBagels– IEatBagels2018年08月21日 16:02:40 +00:00Commented Aug 21, 2018 at 16:02
-
\$\begingroup\$ no I can't , it has to be on console and no use of json \$\endgroup\$ricardo– ricardo2018年08月21日 17:53:43 +00:00Commented Aug 21, 2018 at 17:53
-
\$\begingroup\$ @JᴀʏMᴇᴇ - because it's simple, there should be no impediment to including the whole program. It can be more difficult if the program has hundreds of source files, for example. \$\endgroup\$Toby Speight– Toby Speight2018年08月30日 07:07:19 +00:00Commented Aug 30, 2018 at 7:07
1 Answer 1
As I correctly understood, you want to export matrix in text file. If its true, your code contains some mistakes:
for (int j = 0; j < matrix.GetLength(1) - 1; j++)
should be without decreasing length by 1 and Console.WriteLine("\n");
should be sw.WriteLine();
Also there is a not good idea to ask user to write a path. You could try to use SaveFileDialog
instead.
Full solution
class Program
{
[STAThread]
static void Main(string[] args)
{
int[,] matrix = new int[3, 2]
{
{1, 2},
{3, 4},
{5, 6}
};
ExportData(matrix);
}
private static void ExportData(int[,] matrix)
{
var saveFileDialog = new SaveFileDialog
{
Filter = "Text files (*.txt)|*.txt|All files (*.*)|*.*",
FileName = "export.txt"
};
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
using (StreamWriter streamWriter = new StreamWriter(saveFileDialog.FileName))
{
for(int i = 0; i < matrix.GetLength(0); i++)
{
for(int j = 0; j< matrix.GetLength(1); j++)
{
streamWriter.Write($"\t{matrix[i, j]}\t");
}
streamWriter.WriteLine();
}
}
}
}
}
Just don't forget to add reference to System.Windows.Forms