简体   繁体   中英

Opening a File with an unknown name. C#

I am trying to open a file in C#. I am not sure what the file name will be. The user must enter a year, and this will determine the file name. For instance, if the user enters 2012 the file name is @"C:\\Users\\Marina\\Documents\\Excel Files\\2012.txt" .

My code is as follows:

using System;
using System.Windows.Forms;
using System.IO;

string yearEntered = newDate.Text;
var openFile = File.Open(@"C: \Users\Marina\Documents\Excel Files" + yearEntered + ".txt");

newDate is a textbox I have created on Form1 .

I get an error saying:

No overload for method 'Open' takes 1 arguments". Error code CS1501.

The problem is quite clear, you haven't specified the correct number of arguments for the Open method. Try adding a FileMode.

File.Open(@"C: \Users\Marina\Documents\Excel Files" + yearEntered + ".txt", FileMode.Open);

You need to enter FileMode after the file name, example:

File.Open(@"d:\file1.txt", FileMode.Create);

Take a look at this link:
https://msdn.microsoft.com/en-us/library/system.io.filemode(v=vs.110).aspx

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM