У меня возникла проблема с открытием файла в связанной с ним программе. Сначала я дважды щелкаю по файлу, нажимаю «Открыть с ...», затем я нажимаю свой путь в папку «Отладка» в файле проекта моей программы и запускаю исполняемый файл. Это должно имитировать открытие файла в связанной с ним программе, как если бы программа была фактически установлена на моем компьютере.При двойном щелчке по связанному файлу файл не открывается и не запускается программа
Вот весь код из Program.cs:
namespace TriviaAuthor_v10
{
static class Program
{
[STAThread]
static void Main(string[] args)
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new frmSplashScreen());
if (args.Length > 0)
Application.Run(new frmMain(args[0]));
else
Application.Run(new frmMain());
}
}
}
Теперь вот код для двух конструкторов для главной формы:
public frmMain(string autoopenfilepath)
{
InitializeComponent();
filepath = autoopenfilepath;
OpenTheFile(filepath);
}
public frmMain()
{
InitializeComponent();
}
А вот код для открытия файла:
private void OpenTheFile(string ThisFilePath)
{
// First we get the filename.
filename = Path.GetFileName(ThisFilePath);
FilenameSansExtension = Path.GetFileNameWithoutExtension(ThisFilePath);
// Create a file stream.
FileStream fs = new FileStream(ThisFilePath, FileMode.Open, FileAccess.Read);
// Create the writer for data.
BinaryReader br = new BinaryReader(fs);
GameInfo.GameTitle = br.ReadString();
GameInfo.GameAuthor = br.ReadString();
GameInfo.DateCreated = br.ReadString();
GameInfo.NumberOfQuestions = br.ReadInt32();
GameInfo.TitlePageImagePresent = br.ReadBoolean();
GameInfo.TitlePageImage = br.ReadString();
GameInfo.IntroScreenAudioPresent = br.ReadBoolean();
GameInfo.IntroScreenAudio = br.ReadString();
GameInfo.FinalScoreAudioPresent = br.ReadBoolean();
GameInfo.FinalScoreAudio = br.ReadString();
GameInfo.ActiveQuestion = br.ReadInt32();
if (GameInfo.NumberOfQuestions > 0)
{
for (int i = 0; i < GameInfo.NumberOfQuestions; i++)
{
clsQuestionClass Question = new clsQuestionClass();
Question.NewQuestion = br.ReadString();
Question.Points = br.ReadInt32();
Question.QuestionType = br.ReadInt32();
Question.QuestionImagePresent = br.ReadBoolean();
Question.QuestionImage = br.ReadString();
Question.QuestionAudioPresent = br.ReadBoolean();
Question.QuestionAudio = br.ReadString();
Question.IncludeTimer = br.ReadBoolean();
Question.TimerTime = br.ReadInt32();
Question.TickTock = br.ReadBoolean();
Question.AIsChecked = br.ReadBoolean();
Question.AnswerA = br.ReadString();
Question.AIsCorrect = br.ReadBoolean();
Question.BIsChecked = br.ReadBoolean();
Question.AnswerB = br.ReadString();
Question.BIsCorrect = br.ReadBoolean();
Question.CIsChecked = br.ReadBoolean();
Question.AnswerC = br.ReadString();
Question.CIsCorrect = br.ReadBoolean();
Question.DIsChecked = br.ReadBoolean();
Question.AnswerD = br.ReadString();
Question.DIsCorrect = br.ReadBoolean();
Question.TrueOrFalse = br.ReadBoolean();
Question.FillInBlankAnswer = br.ReadString();
Question.AnswerResponseImagePresent = br.ReadBoolean();
Question.AnswerResponseImage = br.ReadString(); ;
Question.CorrectAnswerResponse = br.ReadString();
Question.IncorrectAnswerResponse = br.ReadString();
Question.CorrectAnswerResponseAudioPresent = br.ReadBoolean();
Question.CorrectAnswerResponseAudio = br.ReadString();
Question.IncorrectAnswerResponseAudioPresent = br.ReadBoolean();
Question.IncorrectAnswerResponseAudio = br.ReadString();
Questions.Add(Question);
Questions.Count();
}
}
fs.Close();
br.Close();
QuestionIndex = GameInfo.ActiveQuestion;
LoadGameIntoGameGUI(Questions[QuestionIndex]);
this.Text = "Trivia Author v1.0 - " + FilenameSansExtension;
ProjectNeedsSaving = false;
saveAsToolStripMenuItem.Enabled = closeprojecttoolStripMenuItem1.Enabled = exportgametoolStripMenuItem.Enabled =
printToolStripMenuItem.Enabled = printPreviewToolStripMenuItem.Enabled = tsbtnProjectClose.Visible =
ProjectIsOpen = saveToolStripMenuItem.Enabled = tsbtnSaveProject.Enabled = btnShowProjectReview.Enabled = true;
UpdateGameSummary();
}
Примечание: «OpenTheFile (string ThisFilePath)» используется для открытия файла с использованием OpenFileDialog и когда я пытаюсь открыть файл, дважды щелкнув по нему.
Так вот проблема: когда я запускаю программу в Visual Studio 2013, а затем открываю файл (используя OpenFileDialog), файл открывается без проблем. Но когда я пытаюсь открыть файл, дважды щелкнув его и открыв его с исполняемым файлом в папке Debug программы, я вижу заставку программы, а затем программа прерывается. Это
выглядит так, как будто путь файла передается на «OpenTheFile()» правильно. И поскольку программа работает за пределами Visual Studio, я не получаю сообщений об ошибках, даже не из операционной системы.
Что делает метод 'AutoOpenFile'? – Guffa
Что происходит, когда вы переходите через код. Вы видите что-то, что выделяется сразу, что привлечет внимание к потенциальной проблеме ..? вы пытались добавить 'FileShare.Read' в эту строку ' FileStream fs = new FileStream (ThisFilePath, FileMode.Open, FileAccess.Read); ' – MethodMan
Вы можете использовать' try' 'catch' с' AutoOpenFile (путь к файлу); ' и получить информацию об исключении (в файл или окно сообщения). –