c# - 使用文件目录作为参数
问题描述
已编辑:为错误道歉-我理解的不是很清楚。
我创建了一个类库,我想用多个方法/函数填充它。我正在研究其中一种方法,但是我正在努力使用自定义目录来使用该方法。
请参阅类库中的方法代码:
public class SharpFuntions
{
public static void CreateFile(string location){
string path = location;
try
{
// Delete the file if it exists.
if (File.Exists(path))
{
File.Delete(path);
}
// Create the file.
File.Create(path);
{
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
现在,当我尝试调用此函数并使用目录时,它不会通过。见下文:
static void Main(string[] args)
{
SharpFuntions.CreateFile(@"C:\User\Text.txt");
}
我不确定上述是否可行。我只想能够调用该函数,并且每次使用它时都可能能够插入不同的目录/文件名。
所以我知道下面的工作,但是我不想硬编码目录/文件名
public class SharpFuntions
{
public static void CreateFile(){
string path = @"c:\temp\MyTest2.txt";
try
{
// Delete the file if it exists.
if (File.Exists(path))
{
File.Delete(path);
}
// Create the file.
File.Create(path)
{
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
解决方案
创建或覆盖指定路径中的文件。
路径类型:System.String
要创建的文件的路径和名称。
删除指定的文件。
确定指定的文件是否存在。
SharpFuntions.CreateFile(@"C:\User");
...
// path is not a file name, it will never work
File.Create(path);
您展示的所有方法都没有使用路径,它们使用文件名。你需要改变它
一个更好的例子
public static void CreateFile(string fileName)
{
try
{
// Delete the file if it exists.
if (File.Exists(fileName))
{
// Note that no lock is put on the
// file and the possibility exists
// that another process could do
// something with it between
// the calls to Exists and Delete.
File.Delete(fileName);
}
// create empty file
using (File.Create(fileName));
// Create the file.
//using (FileStream fs = File.Create(fileName))
//{
// Byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
// Add some information to the file.
// fs.Write(info, 0, info.Length);
//}
// Open the stream and read it back.
//using (StreamReader sr = File.OpenText(fileName))
//{
// string s = "";
// while ((s = sr.ReadLine()) != null)
// {
// Console.WriteLine(s);
// }
//}
}
catch (Exception ex)
{
// log
// message
// output to a console, or something
Console.WriteLine(ex.ToString());
}
}
用法
string fileName = @"c:\temp\MyTest.txt";
CreateFile(fileName);
更新
我已经更新了代码以创建一个空文件,如果这是你想要的
推荐阅读
- flutter - Flutter Dropdown 默认值
- asp.net-web-api - WebAPI 邮递员不调用 Post
- spring-boot - Spring boot 2 - 如何将所有响应标头发送到客户端?
- excel - 如何在不连续的列中返回连续的第一个非空白单元格?
- c++ - 如何使用子项目创建 Makefile
- xamarin - Xamarin 在页面中创建滑动页面
- c++ - 如何解释 IDA Pro 生成的这些代码?
- javascript - onClick、onChange、onLoad 在我的科尔多瓦项目中不起作用
- html - 当 webkit 在 Chrome 和 Safari 中显示不同时发生了什么?当前浏览器版本的浏览器前缀是否已更改?
- php - Laravel 使用 docker 时不加载样式资源