Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
317 views
in Technique[技术] by (71.8m points)

How to create file and return it via FileResult in ASP.NET MVC?

I have to create and return file in my aplication ASP.net MVC aplication. The file type should be normal .txt file. I know that i can return FileResult but i don't know how to use it.

public FilePathResult GetFile()
{
string name = "me.txt";

FileInfo info = new FileInfo(name);
if (!info.Exists)
{
    using (StreamWriter writer = info.CreateText())
    {
        writer.WriteLine("Hello, I am a new text file");

    }
}

return File(name, "text/plain");
}

This code doesn't work. Why? How to do it with stream result?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

EDIT ( If you want the stream try this: )

public FileStreamResult GetFile()
{
    string name = "me.txt";

    FileInfo info = new FileInfo(name);
    if (!info.Exists)
    {
        using (StreamWriter writer = info.CreateText())
        {
            writer.WriteLine("Hello, I am a new text file");

        }
    }

    return File(info.OpenRead(), "text/plain");

}

You could try something like this..

public FilePathResult GetFile()
{
    string name = "me.txt";

    FileInfo info = new FileInfo(name);
    if (!info.Exists)
    {
        using (StreamWriter writer = info.CreateText())
        {
            writer.WriteLine("Hello, I am a new text file");

        }
    }

    return File(name, "text/plain");

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...