SftpTests.cs 228 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478
  1. using System.Diagnostics;
  2. using Renci.SshNet.Common;
  3. using Renci.SshNet.IntegrationTests.Common;
  4. using Renci.SshNet.Sftp;
  5. namespace Renci.SshNet.IntegrationTests
  6. {
  7. // TODO: DeleteDirectory (fail + success
  8. // TODO: DeleteFile (fail + success
  9. // TODO: Delete (fail + success
  10. [TestClass]
  11. public class SftpTests : TestBase
  12. {
  13. private IConnectionInfoFactory _connectionInfoFactory;
  14. private IConnectionInfoFactory _adminConnectionInfoFactory;
  15. private IRemotePathTransformation _remotePathTransformation;
  16. [TestInitialize]
  17. public void SetUp()
  18. {
  19. _connectionInfoFactory = new LinuxVMConnectionFactory(SshServerHostName, SshServerPort);
  20. _adminConnectionInfoFactory = new LinuxAdminConnectionFactory(SshServerHostName, SshServerPort);
  21. _remotePathTransformation = RemotePathTransformation.ShellQuote;
  22. }
  23. [TestMethod]
  24. [DynamicData(nameof(GetSftpUploadFileFileStreamData), DynamicDataSourceType.Method)]
  25. public void Sftp_UploadFile_FileStream(int size)
  26. {
  27. var file = CreateTempFile(size);
  28. using (var fs = new FileStream(file, FileMode.Open, FileAccess.Read, FileShare.Read))
  29. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  30. {
  31. client.Connect();
  32. var remoteFile = GenerateUniqueRemoteFileName();
  33. if (client.Exists(remoteFile))
  34. {
  35. client.Delete(remoteFile);
  36. }
  37. try
  38. {
  39. client.UploadFile(fs, remoteFile);
  40. using (var memoryStream = new MemoryStream(size))
  41. {
  42. DownloadFileRandomMethod(client, remoteFile, memoryStream);
  43. memoryStream.Position = 0;
  44. Assert.AreEqual(CreateFileHash(file), CreateHash(memoryStream));
  45. }
  46. }
  47. finally
  48. {
  49. if (client.Exists(remoteFile))
  50. {
  51. client.Delete(remoteFile);
  52. }
  53. }
  54. }
  55. }
  56. [TestMethod]
  57. public void Sftp_ConnectDisconnect_Serial()
  58. {
  59. const int iterations = 100;
  60. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  61. {
  62. for (var i = 1; i <= iterations; i++)
  63. {
  64. client.Connect();
  65. client.Disconnect();
  66. }
  67. }
  68. }
  69. [TestMethod]
  70. public void Sftp_ConnectDisconnect_Parallel()
  71. {
  72. const int iterations = 10;
  73. const int threads = 5;
  74. var startEvent = new ManualResetEvent(false);
  75. var tasks = Enumerable.Range(1, threads).Select(i =>
  76. {
  77. return Task.Factory.StartNew(() =>
  78. {
  79. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  80. {
  81. startEvent.WaitOne();
  82. for (var j = 0; j < iterations; j++)
  83. {
  84. client.Connect();
  85. client.Disconnect();
  86. }
  87. }
  88. });
  89. }).ToArray();
  90. startEvent.Set();
  91. Task.WaitAll(tasks);
  92. }
  93. [TestMethod]
  94. public void Sftp_BeginUploadFile()
  95. {
  96. const string content = "SftpBeginUploadFile";
  97. var expectedByteCount = (ulong)Encoding.ASCII.GetByteCount(content);
  98. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  99. {
  100. client.Connect();
  101. var remoteFile = GenerateUniqueRemoteFileName();
  102. if (client.Exists(remoteFile))
  103. {
  104. client.Delete(remoteFile);
  105. }
  106. try
  107. {
  108. using (var memoryStream = new MemoryStream(Encoding.ASCII.GetBytes(content)))
  109. {
  110. IAsyncResult asyncResultCallback = null;
  111. using var callbackCalled = new ManualResetEventSlim(false);
  112. var asyncResult = client.BeginUploadFile(memoryStream, remoteFile, ar =>
  113. {
  114. asyncResultCallback = ar;
  115. callbackCalled.Set();
  116. });
  117. Assert.IsTrue(asyncResult.AsyncWaitHandle.WaitOne(10000));
  118. // check async result
  119. var sftpUploadAsyncResult = asyncResult as SftpUploadAsyncResult;
  120. Assert.IsNotNull(sftpUploadAsyncResult);
  121. Assert.IsFalse(sftpUploadAsyncResult.IsUploadCanceled);
  122. Assert.IsTrue(sftpUploadAsyncResult.IsCompleted);
  123. Assert.IsFalse(sftpUploadAsyncResult.CompletedSynchronously);
  124. Assert.AreEqual(expectedByteCount, sftpUploadAsyncResult.UploadedBytes);
  125. Assert.IsTrue(callbackCalled.Wait(10000));
  126. // check async result callback
  127. var sftpUploadAsyncResultCallback = asyncResultCallback as SftpUploadAsyncResult;
  128. Assert.IsNotNull(sftpUploadAsyncResultCallback);
  129. Assert.IsFalse(sftpUploadAsyncResultCallback.IsUploadCanceled);
  130. Assert.IsTrue(sftpUploadAsyncResultCallback.IsCompleted);
  131. Assert.IsFalse(sftpUploadAsyncResultCallback.CompletedSynchronously);
  132. Assert.AreEqual(expectedByteCount, sftpUploadAsyncResultCallback.UploadedBytes);
  133. }
  134. // check uploaded file
  135. using (var memoryStream = new MemoryStream())
  136. {
  137. DownloadFileRandomMethod(client, remoteFile, memoryStream);
  138. memoryStream.Position = 0;
  139. var remoteContent = Encoding.ASCII.GetString(memoryStream.ToArray());
  140. Assert.AreEqual(content, remoteContent);
  141. }
  142. }
  143. finally
  144. {
  145. if (client.Exists(remoteFile))
  146. {
  147. client.Delete(remoteFile);
  148. }
  149. }
  150. }
  151. }
  152. [TestMethod]
  153. public void Sftp_Create_ExistingFile()
  154. {
  155. var encoding = Encoding.UTF8;
  156. var initialContent = "Gert & Ann & Lisa";
  157. var newContent1 = "Sofie";
  158. var newContent1Bytes = GetBytesWithPreamble(newContent1, encoding);
  159. var newContent2 = "Lisa & Sofie";
  160. var newContent2Bytes = GetBytesWithPreamble(newContent2, encoding);
  161. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  162. {
  163. client.Connect();
  164. var remoteFile = GenerateUniqueRemoteFileName();
  165. if (client.Exists(remoteFile))
  166. {
  167. client.DeleteFile(remoteFile);
  168. }
  169. try
  170. {
  171. client.WriteAllText(remoteFile, initialContent);
  172. #region Write less bytes than the current content, overwriting part of that content
  173. using (var fs = client.Create(remoteFile))
  174. using (var sw = new StreamWriter(fs, encoding))
  175. {
  176. sw.Write(newContent1);
  177. }
  178. var actualContent1 = client.ReadAllBytes(remoteFile);
  179. CollectionAssert.AreEqual(newContent1Bytes, actualContent1);
  180. #endregion Write less bytes than the current content, overwriting part of that content
  181. #region Write more bytes than the current content, overwriting and appending to that content
  182. using (var fs = client.Create(remoteFile))
  183. using (var sw = new StreamWriter(fs, encoding))
  184. {
  185. sw.Write(newContent2);
  186. }
  187. var actualContent2 = client.ReadAllBytes(remoteFile);
  188. CollectionAssert.AreEqual(newContent2Bytes, actualContent2);
  189. #endregion Write more bytes than the current content, overwriting and appending to that content
  190. }
  191. finally
  192. {
  193. if (client.Exists(remoteFile))
  194. {
  195. client.DeleteFile(remoteFile);
  196. }
  197. }
  198. }
  199. }
  200. [TestMethod]
  201. public void Sftp_Create_DirectoryDoesNotExist()
  202. {
  203. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  204. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  205. {
  206. client.Connect();
  207. if (client.Exists(remoteFile))
  208. {
  209. client.DeleteFile(remoteFile);
  210. }
  211. SftpFileStream fs = null;
  212. try
  213. {
  214. fs = client.Create(remoteFile);
  215. Assert.Fail();
  216. }
  217. catch (SftpPathNotFoundException ex)
  218. {
  219. Assert.IsNull(ex.InnerException);
  220. Assert.AreEqual("No such file", ex.Message);
  221. }
  222. finally
  223. {
  224. fs?.Dispose();
  225. if (client.Exists(remoteFile))
  226. {
  227. client.DeleteFile(remoteFile);
  228. }
  229. }
  230. }
  231. }
  232. [TestMethod]
  233. public void Sftp_Create_FileDoesNotExist()
  234. {
  235. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  236. {
  237. client.BufferSize = 512 * 1024;
  238. client.Connect();
  239. var remoteFile = GenerateUniqueRemoteFileName();
  240. if (client.Exists(remoteFile))
  241. {
  242. client.DeleteFile(remoteFile);
  243. }
  244. try
  245. {
  246. using (var imageStream = GetData("resources.issue #70.png"))
  247. {
  248. using (var fs = client.Create(remoteFile))
  249. {
  250. imageStream.CopyTo(fs);
  251. }
  252. using (var memoryStream = new MemoryStream())
  253. {
  254. DownloadFileRandomMethod(client, remoteFile, memoryStream);
  255. memoryStream.Position = 0;
  256. imageStream.Position = 0;
  257. Assert.AreEqual(CreateHash(imageStream), CreateHash(memoryStream));
  258. }
  259. }
  260. }
  261. finally
  262. {
  263. if (client.Exists(remoteFile))
  264. {
  265. client.DeleteFile(remoteFile);
  266. }
  267. }
  268. }
  269. }
  270. [TestMethod]
  271. public void Sftp_AppendAllLines_NoEncoding_ExistingFile()
  272. {
  273. var initialContent = "\u0100ert & Ann";
  274. IEnumerable<string> linesToAppend = new[] { "Forever", "&", "\u0116ver" };
  275. var expectedContent = initialContent + string.Join(Environment.NewLine, linesToAppend) +
  276. Environment.NewLine;
  277. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  278. {
  279. client.Connect();
  280. var remoteFile = GenerateUniqueRemoteFileName();
  281. if (client.Exists(remoteFile))
  282. {
  283. client.DeleteFile(remoteFile);
  284. }
  285. try
  286. {
  287. client.WriteAllText(remoteFile, initialContent);
  288. client.AppendAllLines(remoteFile, linesToAppend);
  289. var text = client.ReadAllText(remoteFile);
  290. Assert.AreEqual(expectedContent, text);
  291. // ensure we didn't write an UTF-8 BOM
  292. using (var fs = client.OpenRead(remoteFile))
  293. {
  294. var firstByte = fs.ReadByte();
  295. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  296. }
  297. }
  298. finally
  299. {
  300. if (client.Exists(remoteFile))
  301. {
  302. client.DeleteFile(remoteFile);
  303. }
  304. }
  305. }
  306. }
  307. [TestMethod]
  308. public void Sftp_AppendAllLines_NoEncoding_DirectoryDoesNotExist()
  309. {
  310. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  311. IEnumerable<string> linesToAppend = new[] { "\u0139isa", "&", "Sofie" };
  312. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  313. {
  314. client.Connect();
  315. if (client.Exists(remoteFile))
  316. {
  317. client.DeleteFile(remoteFile);
  318. }
  319. try
  320. {
  321. client.AppendAllLines(remoteFile, linesToAppend);
  322. Assert.Fail();
  323. }
  324. catch (SftpPathNotFoundException ex)
  325. {
  326. Assert.IsNull(ex.InnerException);
  327. Assert.AreEqual("No such file", ex.Message);
  328. }
  329. finally
  330. {
  331. if (client.Exists(remoteFile))
  332. {
  333. client.DeleteFile(remoteFile);
  334. }
  335. }
  336. }
  337. }
  338. [TestMethod]
  339. public void Sftp_AppendAllLines_NoEncoding_FileDoesNotExist()
  340. {
  341. IEnumerable<string> linesToAppend = new[] { "\u0139isa", "&", "Sofie" };
  342. var expectedContent = string.Join(Environment.NewLine, linesToAppend) + Environment.NewLine;
  343. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  344. {
  345. client.Connect();
  346. var remoteFile = GenerateUniqueRemoteFileName();
  347. if (client.Exists(remoteFile))
  348. {
  349. client.DeleteFile(remoteFile);
  350. }
  351. try
  352. {
  353. client.AppendAllLines(remoteFile, linesToAppend);
  354. var text = client.ReadAllText(remoteFile);
  355. Assert.AreEqual(expectedContent, text);
  356. // ensure we didn't write an UTF-8 BOM
  357. using (var fs = client.OpenRead(remoteFile))
  358. {
  359. var firstByte = fs.ReadByte();
  360. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  361. }
  362. }
  363. finally
  364. {
  365. if (client.Exists(remoteFile))
  366. {
  367. client.DeleteFile(remoteFile);
  368. }
  369. }
  370. }
  371. }
  372. [TestMethod]
  373. public void Sftp_AppendAllText_NoEncoding_ExistingFile()
  374. {
  375. var initialContent = "\u0100ert & Ann";
  376. var contentToAppend = "Forever&\u0116ver";
  377. var expectedContent = initialContent + contentToAppend;
  378. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  379. {
  380. client.Connect();
  381. var remoteFile = GenerateUniqueRemoteFileName();
  382. if (client.Exists(remoteFile))
  383. {
  384. client.DeleteFile(remoteFile);
  385. }
  386. try
  387. {
  388. client.WriteAllText(remoteFile, initialContent);
  389. client.AppendAllText(remoteFile, contentToAppend);
  390. var text = client.ReadAllText(remoteFile);
  391. Assert.AreEqual(expectedContent, text);
  392. // ensure we didn't write an UTF-8 BOM
  393. using (var fs = client.OpenRead(remoteFile))
  394. {
  395. var firstByte = fs.ReadByte();
  396. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  397. }
  398. }
  399. finally
  400. {
  401. if (client.Exists(remoteFile))
  402. {
  403. client.DeleteFile(remoteFile);
  404. }
  405. }
  406. }
  407. }
  408. [TestMethod]
  409. public void Sftp_AppendAllText_NoEncoding_DirectoryDoesNotExist()
  410. {
  411. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  412. var contentToAppend = "Forever&\u0116ver";
  413. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  414. {
  415. client.Connect();
  416. if (client.Exists(remoteFile))
  417. {
  418. client.DeleteFile(remoteFile);
  419. }
  420. try
  421. {
  422. client.AppendAllText(remoteFile, contentToAppend);
  423. Assert.Fail();
  424. }
  425. catch (SftpPathNotFoundException ex)
  426. {
  427. Assert.IsNull(ex.InnerException);
  428. Assert.AreEqual("No such file", ex.Message);
  429. }
  430. finally
  431. {
  432. if (client.Exists(remoteFile))
  433. {
  434. client.DeleteFile(remoteFile);
  435. }
  436. }
  437. }
  438. }
  439. [TestMethod]
  440. public void Sftp_AppendAllText_NoEncoding_FileDoesNotExist()
  441. {
  442. var contentToAppend = "Forever&\u0116ver";
  443. var expectedContent = contentToAppend;
  444. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  445. {
  446. client.Connect();
  447. var remoteFile = GenerateUniqueRemoteFileName();
  448. if (client.Exists(remoteFile))
  449. {
  450. client.DeleteFile(remoteFile);
  451. }
  452. try
  453. {
  454. client.AppendAllText(remoteFile, contentToAppend);
  455. var text = client.ReadAllText(remoteFile);
  456. Assert.AreEqual(expectedContent, text);
  457. // ensure we didn't write an UTF-8 BOM
  458. using (var fs = client.OpenRead(remoteFile))
  459. {
  460. var firstByte = fs.ReadByte();
  461. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  462. }
  463. }
  464. finally
  465. {
  466. if (client.Exists(remoteFile))
  467. {
  468. client.DeleteFile(remoteFile);
  469. }
  470. }
  471. }
  472. }
  473. [TestMethod]
  474. public void Sftp_AppendText_NoEncoding_ExistingFile()
  475. {
  476. var initialContent = "\u0100ert & Ann";
  477. var contentToAppend = "Forever&\u0116ver";
  478. var expectedContent = initialContent + contentToAppend;
  479. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  480. {
  481. client.Connect();
  482. var remoteFile = GenerateUniqueRemoteFileName();
  483. if (client.Exists(remoteFile))
  484. {
  485. client.DeleteFile(remoteFile);
  486. }
  487. try
  488. {
  489. client.WriteAllText(remoteFile, initialContent);
  490. using (var sw = client.AppendText(remoteFile))
  491. {
  492. sw.Write(contentToAppend);
  493. }
  494. var text = client.ReadAllText(remoteFile);
  495. Assert.AreEqual(expectedContent, text);
  496. // ensure we didn't write an UTF-8 BOM
  497. using (var fs = client.OpenRead(remoteFile))
  498. {
  499. var firstByte = fs.ReadByte();
  500. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  501. }
  502. }
  503. finally
  504. {
  505. if (client.Exists(remoteFile))
  506. {
  507. client.DeleteFile(remoteFile);
  508. }
  509. }
  510. }
  511. }
  512. [TestMethod]
  513. public void Sftp_AppendText_NoEncoding_DirectoryDoesNotExist()
  514. {
  515. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  516. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  517. {
  518. client.Connect();
  519. if (client.Exists(remoteFile))
  520. {
  521. client.DeleteFile(remoteFile);
  522. }
  523. StreamWriter sw = null;
  524. try
  525. {
  526. sw = client.AppendText(remoteFile);
  527. Assert.Fail();
  528. }
  529. catch (SftpPathNotFoundException ex)
  530. {
  531. Assert.IsNull(ex.InnerException);
  532. Assert.AreEqual("No such file", ex.Message);
  533. }
  534. finally
  535. {
  536. sw?.Dispose();
  537. if (client.Exists(remoteFile))
  538. {
  539. client.DeleteFile(remoteFile);
  540. }
  541. }
  542. }
  543. }
  544. [TestMethod]
  545. public void Sftp_AppendText_NoEncoding_FileDoesNotExist()
  546. {
  547. var contentToAppend = "\u0100ert & Ann";
  548. var expectedContent = contentToAppend;
  549. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  550. {
  551. client.Connect();
  552. var remoteFile = GenerateUniqueRemoteFileName();
  553. if (client.Exists(remoteFile))
  554. {
  555. client.DeleteFile(remoteFile);
  556. }
  557. try
  558. {
  559. using (var sw = client.AppendText(remoteFile))
  560. {
  561. sw.Write(contentToAppend);
  562. }
  563. // ensure we didn't write an UTF-8 BOM
  564. using (var fs = client.OpenRead(remoteFile))
  565. {
  566. var firstByte = fs.ReadByte();
  567. Assert.AreEqual(Encoding.UTF8.GetBytes(expectedContent)[0], firstByte);
  568. }
  569. }
  570. finally
  571. {
  572. if (client.Exists(remoteFile))
  573. {
  574. client.DeleteFile(remoteFile);
  575. }
  576. }
  577. }
  578. }
  579. [TestMethod]
  580. public void Sftp_AppendAllLines_Encoding_ExistingFile()
  581. {
  582. var initialContent = "\u0100ert & Ann";
  583. IEnumerable<string> linesToAppend = new[] { "Forever", "&", "\u0116ver" };
  584. var expectedContent = initialContent + string.Join(Environment.NewLine, linesToAppend) +
  585. Environment.NewLine;
  586. var encoding = GetRandomEncoding();
  587. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  588. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  589. {
  590. client.Connect();
  591. var remoteFile = GenerateUniqueRemoteFileName();
  592. if (client.Exists(remoteFile))
  593. {
  594. client.DeleteFile(remoteFile);
  595. }
  596. try
  597. {
  598. client.WriteAllText(remoteFile, initialContent, encoding);
  599. client.AppendAllLines(remoteFile, linesToAppend, encoding);
  600. var text = client.ReadAllText(remoteFile, encoding);
  601. Assert.AreEqual(expectedContent, text);
  602. var actualBytes = client.ReadAllBytes(remoteFile);
  603. CollectionAssert.AreEqual(expectedBytes, actualBytes);
  604. }
  605. finally
  606. {
  607. if (client.Exists(remoteFile))
  608. {
  609. client.DeleteFile(remoteFile);
  610. }
  611. }
  612. }
  613. }
  614. [TestMethod]
  615. public void Sftp_AppendAllLines_Encoding_DirectoryDoesNotExist()
  616. {
  617. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  618. IEnumerable<string> linesToAppend = new[] { "Forever", "&", "\u0116ver" };
  619. var encoding = GetRandomEncoding();
  620. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  621. {
  622. client.Connect();
  623. if (client.Exists(remoteFile))
  624. {
  625. client.DeleteFile(remoteFile);
  626. }
  627. try
  628. {
  629. client.AppendAllLines(remoteFile, linesToAppend, encoding);
  630. Assert.Fail();
  631. }
  632. catch (SftpPathNotFoundException ex)
  633. {
  634. Assert.IsNull(ex.InnerException);
  635. Assert.AreEqual("No such file", ex.Message);
  636. }
  637. finally
  638. {
  639. if (client.Exists(remoteFile))
  640. {
  641. client.DeleteFile(remoteFile);
  642. }
  643. }
  644. }
  645. }
  646. [TestMethod]
  647. public void Sftp_AppendAllLines_Encoding_FileDoesNotExist()
  648. {
  649. IEnumerable<string> linesToAppend = new[] { "\u0139isa", "&", "Sofie" };
  650. var expectedContent = string.Join(Environment.NewLine, linesToAppend) + Environment.NewLine;
  651. var encoding = GetRandomEncoding();
  652. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  653. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  654. {
  655. client.Connect();
  656. var remoteFile = GenerateUniqueRemoteFileName();
  657. if (client.Exists(remoteFile))
  658. {
  659. client.DeleteFile(remoteFile);
  660. }
  661. try
  662. {
  663. client.AppendAllLines(remoteFile, linesToAppend, encoding);
  664. var text = client.ReadAllText(remoteFile, encoding);
  665. Assert.AreEqual(expectedContent, text);
  666. var actualBytes = client.ReadAllBytes(remoteFile);
  667. CollectionAssert.AreEqual(expectedBytes, actualBytes);
  668. }
  669. finally
  670. {
  671. if (client.Exists(remoteFile))
  672. {
  673. client.DeleteFile(remoteFile);
  674. }
  675. }
  676. }
  677. }
  678. [TestMethod]
  679. public void Sftp_AppendAllText_Encoding_ExistingFile()
  680. {
  681. var initialContent = "\u0100ert & Ann";
  682. var contentToAppend = "Forever&\u0116ver";
  683. var expectedContent = initialContent + contentToAppend;
  684. var encoding = GetRandomEncoding();
  685. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  686. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  687. {
  688. client.Connect();
  689. var remoteFile = GenerateUniqueRemoteFileName();
  690. if (client.Exists(remoteFile))
  691. {
  692. client.DeleteFile(remoteFile);
  693. }
  694. try
  695. {
  696. client.WriteAllText(remoteFile, initialContent, encoding);
  697. client.AppendAllText(remoteFile, contentToAppend, encoding);
  698. var text = client.ReadAllText(remoteFile, encoding);
  699. Assert.AreEqual(expectedContent, text);
  700. var actualBytes = client.ReadAllBytes(remoteFile);
  701. CollectionAssert.AreEqual(expectedBytes, actualBytes);
  702. }
  703. finally
  704. {
  705. if (client.Exists(remoteFile))
  706. {
  707. client.DeleteFile(remoteFile);
  708. }
  709. }
  710. }
  711. }
  712. [TestMethod]
  713. public void Sftp_AppendAllText_Encoding_DirectoryDoesNotExist()
  714. {
  715. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  716. const string contentToAppend = "Forever&\u0116ver";
  717. var encoding = GetRandomEncoding();
  718. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  719. {
  720. client.Connect();
  721. if (client.Exists(remoteFile))
  722. {
  723. client.DeleteFile(remoteFile);
  724. }
  725. try
  726. {
  727. client.AppendAllText(remoteFile, contentToAppend, encoding);
  728. Assert.Fail();
  729. }
  730. catch (SftpPathNotFoundException ex)
  731. {
  732. Assert.IsNull(ex.InnerException);
  733. Assert.AreEqual("No such file", ex.Message);
  734. }
  735. finally
  736. {
  737. if (client.Exists(remoteFile))
  738. {
  739. client.DeleteFile(remoteFile);
  740. }
  741. }
  742. }
  743. }
  744. [TestMethod]
  745. public void Sftp_AppendAllText_Encoding_FileDoesNotExist()
  746. {
  747. const string contentToAppend = "Forever&\u0116ver";
  748. var expectedContent = contentToAppend;
  749. var encoding = GetRandomEncoding();
  750. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  751. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  752. {
  753. client.Connect();
  754. var remoteFile = GenerateUniqueRemoteFileName();
  755. if (client.Exists(remoteFile))
  756. {
  757. client.DeleteFile(remoteFile);
  758. }
  759. try
  760. {
  761. client.AppendAllText(remoteFile, contentToAppend, encoding);
  762. var text = client.ReadAllText(remoteFile, encoding);
  763. Assert.AreEqual(expectedContent, text);
  764. var actualBytes = client.ReadAllBytes(remoteFile);
  765. CollectionAssert.AreEqual(expectedBytes, actualBytes);
  766. }
  767. finally
  768. {
  769. if (client.Exists(remoteFile))
  770. {
  771. client.DeleteFile(remoteFile);
  772. }
  773. }
  774. }
  775. }
  776. [TestMethod]
  777. public void Sftp_AppendText_Encoding_ExistingFile()
  778. {
  779. const string initialContent = "\u0100ert & Ann";
  780. const string contentToAppend = "Forever&\u0116ver";
  781. var expectedContent = initialContent + contentToAppend;
  782. var encoding = GetRandomEncoding();
  783. var expectedBytes = GetBytesWithPreamble(expectedContent, encoding);
  784. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  785. {
  786. client.Connect();
  787. var remoteFile = GenerateUniqueRemoteFileName();
  788. if (client.Exists(remoteFile))
  789. {
  790. client.DeleteFile(remoteFile);
  791. }
  792. try
  793. {
  794. client.WriteAllText(remoteFile, initialContent, encoding);
  795. using (var sw = client.AppendText(remoteFile, encoding))
  796. {
  797. sw.Write(contentToAppend);
  798. }
  799. var text = client.ReadAllText(remoteFile, encoding);
  800. Assert.AreEqual(expectedContent, text);
  801. var actualBytes = client.ReadAllBytes(remoteFile);
  802. CollectionAssert.AreEqual(expectedBytes, actualBytes);
  803. }
  804. finally
  805. {
  806. if (client.Exists(remoteFile))
  807. {
  808. client.DeleteFile(remoteFile);
  809. }
  810. }
  811. }
  812. }
  813. [TestMethod]
  814. public void Sftp_AppendText_Encoding_DirectoryDoesNotExist()
  815. {
  816. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  817. var encoding = GetRandomEncoding();
  818. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  819. {
  820. client.Connect();
  821. if (client.Exists(remoteFile))
  822. {
  823. client.DeleteFile(remoteFile);
  824. }
  825. StreamWriter sw = null;
  826. try
  827. {
  828. sw = client.AppendText(remoteFile, encoding);
  829. Assert.Fail();
  830. }
  831. catch (SftpPathNotFoundException ex)
  832. {
  833. Assert.IsNull(ex.InnerException);
  834. Assert.AreEqual("No such file", ex.Message);
  835. }
  836. finally
  837. {
  838. sw?.Dispose();
  839. if (client.Exists(remoteFile))
  840. {
  841. client.DeleteFile(remoteFile);
  842. }
  843. }
  844. }
  845. }
  846. [TestMethod]
  847. public void Sftp_AppendText_Encoding_FileDoesNotExist()
  848. {
  849. var encoding = GetRandomEncoding();
  850. const string contentToAppend = "\u0100ert & Ann";
  851. var expectedBytes = GetBytesWithPreamble(contentToAppend, encoding);
  852. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  853. {
  854. client.Connect();
  855. var remoteFile = GenerateUniqueRemoteFileName();
  856. if (client.Exists(remoteFile))
  857. {
  858. client.DeleteFile(remoteFile);
  859. }
  860. try
  861. {
  862. using (var sw = client.AppendText(remoteFile, encoding))
  863. {
  864. sw.Write(contentToAppend);
  865. }
  866. var actualBytes = client.ReadAllBytes(remoteFile);
  867. CollectionAssert.AreEqual(expectedBytes, actualBytes);
  868. }
  869. finally
  870. {
  871. if (client.Exists(remoteFile))
  872. {
  873. client.DeleteFile(remoteFile);
  874. }
  875. }
  876. }
  877. }
  878. [TestMethod]
  879. public void Sftp_CreateText_NoEncoding_ExistingFile()
  880. {
  881. var encoding = new UTF8Encoding(false, true);
  882. const string initialContent = "\u0100ert & Ann";
  883. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  884. const string newContent = "\u0116ver";
  885. var newContentBytes = GetBytesWithPreamble(newContent, encoding);
  886. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  887. {
  888. client.Connect();
  889. var remoteFile = GenerateUniqueRemoteFileName();
  890. if (client.Exists(remoteFile))
  891. {
  892. client.DeleteFile(remoteFile);
  893. }
  894. try
  895. {
  896. client.WriteAllText(remoteFile, initialContent);
  897. Assert.AreEqual(initialContentBytes.Length, client.Get(remoteFile).Length);
  898. using (var sw = client.CreateText(remoteFile))
  899. {
  900. sw.Write(newContent);
  901. }
  902. // verify that the file was truncated
  903. Assert.AreEqual(newContentBytes.Length, client.Get(remoteFile).Length);
  904. var text = client.ReadAllText(remoteFile);
  905. Assert.AreEqual(newContent, text);
  906. var actualBytes = client.ReadAllBytes(remoteFile);
  907. CollectionAssert.AreEqual(newContentBytes, actualBytes);
  908. }
  909. finally
  910. {
  911. if (client.Exists(remoteFile))
  912. {
  913. client.DeleteFile(remoteFile);
  914. }
  915. }
  916. }
  917. }
  918. [TestMethod]
  919. public void Sftp_CreateText_NoEncoding_DirectoryDoesNotExist()
  920. {
  921. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  922. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  923. {
  924. client.Connect();
  925. if (client.Exists(remoteFile))
  926. {
  927. client.DeleteFile(remoteFile);
  928. }
  929. StreamWriter sw = null;
  930. try
  931. {
  932. sw = client.CreateText(remoteFile);
  933. Assert.Fail();
  934. }
  935. catch (SftpPathNotFoundException ex)
  936. {
  937. Assert.IsNull(ex.InnerException);
  938. Assert.AreEqual("No such file", ex.Message);
  939. }
  940. finally
  941. {
  942. sw?.Dispose();
  943. if (client.Exists(remoteFile))
  944. {
  945. client.DeleteFile(remoteFile);
  946. }
  947. }
  948. }
  949. }
  950. [TestMethod]
  951. public void Sftp_CreateText_NoEncoding_FileDoesNotExist()
  952. {
  953. var encoding = new UTF8Encoding(false, true);
  954. var initialContent = "\u0100ert & Ann";
  955. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  956. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  957. {
  958. client.Connect();
  959. var remoteFile = GenerateUniqueRemoteFileName();
  960. if (client.Exists(remoteFile))
  961. {
  962. client.DeleteFile(remoteFile);
  963. }
  964. try
  965. {
  966. using (client.CreateText(remoteFile))
  967. {
  968. }
  969. // verify that empty file was created
  970. Assert.IsTrue(client.Exists(remoteFile));
  971. var file = client.GetAttributes(remoteFile);
  972. Assert.AreEqual(0, file.Size);
  973. client.DeleteFile(remoteFile);
  974. using (var sw = client.CreateText(remoteFile))
  975. {
  976. sw.Write(initialContent);
  977. }
  978. // verify that content is written to file
  979. var text = client.ReadAllText(remoteFile);
  980. Assert.AreEqual(initialContent, text);
  981. var actualBytes = client.ReadAllBytes(remoteFile);
  982. CollectionAssert.AreEqual(initialContentBytes, actualBytes);
  983. }
  984. finally
  985. {
  986. if (client.Exists(remoteFile))
  987. {
  988. client.DeleteFile(remoteFile);
  989. }
  990. }
  991. }
  992. }
  993. [TestMethod]
  994. public void Sftp_CreateText_Encoding_ExistingFile()
  995. {
  996. var encoding = GetRandomEncoding();
  997. var initialContent = "\u0100ert & Ann";
  998. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  999. var newContent = "\u0116ver";
  1000. var newContentBytes = GetBytesWithPreamble(newContent, encoding);
  1001. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1002. {
  1003. client.Connect();
  1004. var remoteFile = GenerateUniqueRemoteFileName();
  1005. if (client.Exists(remoteFile))
  1006. {
  1007. client.DeleteFile(remoteFile);
  1008. }
  1009. try
  1010. {
  1011. client.WriteAllText(remoteFile, initialContent, encoding);
  1012. Assert.AreEqual(initialContentBytes.Length, client.Get(remoteFile).Length);
  1013. using (var sw = client.CreateText(remoteFile, encoding))
  1014. {
  1015. sw.Write(newContent);
  1016. }
  1017. // verify that the file was truncated
  1018. Assert.AreEqual(newContentBytes.Length, client.Get(remoteFile).Length);
  1019. var text = client.ReadAllText(remoteFile);
  1020. Assert.AreEqual(newContent, text);
  1021. var actualBytes = client.ReadAllBytes(remoteFile);
  1022. CollectionAssert.AreEqual(newContentBytes, actualBytes);
  1023. }
  1024. finally
  1025. {
  1026. if (client.Exists(remoteFile))
  1027. {
  1028. client.DeleteFile(remoteFile);
  1029. }
  1030. }
  1031. }
  1032. }
  1033. [TestMethod]
  1034. public void Sftp_CreateText_Encoding_DirectoryDoesNotExist()
  1035. {
  1036. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1037. var encoding = GetRandomEncoding();
  1038. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1039. {
  1040. client.Connect();
  1041. if (client.Exists(remoteFile))
  1042. {
  1043. client.DeleteFile(remoteFile);
  1044. }
  1045. StreamWriter sw = null;
  1046. try
  1047. {
  1048. sw = client.CreateText(remoteFile, encoding);
  1049. Assert.Fail();
  1050. }
  1051. catch (SftpPathNotFoundException ex)
  1052. {
  1053. Assert.IsNull(ex.InnerException);
  1054. Assert.AreEqual("No such file", ex.Message);
  1055. }
  1056. finally
  1057. {
  1058. sw?.Dispose();
  1059. if (client.Exists(remoteFile))
  1060. {
  1061. client.DeleteFile(remoteFile);
  1062. }
  1063. }
  1064. }
  1065. }
  1066. [TestMethod]
  1067. public void Sftp_CreateText_Encoding_FileDoesNotExist()
  1068. {
  1069. var encoding = GetRandomEncoding();
  1070. var initialContent = "\u0100ert & Ann";
  1071. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  1072. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1073. {
  1074. client.Connect();
  1075. var remoteFile = GenerateUniqueRemoteFileName();
  1076. if (client.Exists(remoteFile))
  1077. {
  1078. client.DeleteFile(remoteFile);
  1079. }
  1080. try
  1081. {
  1082. using (client.CreateText(remoteFile, encoding))
  1083. {
  1084. }
  1085. // verify that file containing only preamble was created
  1086. Assert.IsTrue(client.Exists(remoteFile));
  1087. var file = client.GetAttributes(remoteFile);
  1088. Assert.AreEqual(encoding.GetPreamble().Length, file.Size);
  1089. client.DeleteFile(remoteFile);
  1090. using (var sw = client.CreateText(remoteFile, encoding))
  1091. {
  1092. sw.Write(initialContent);
  1093. }
  1094. // verify that content is written to file
  1095. var text = client.ReadAllText(remoteFile, encoding);
  1096. Assert.AreEqual(initialContent, text);
  1097. var actualBytes = client.ReadAllBytes(remoteFile);
  1098. CollectionAssert.AreEqual(initialContentBytes, actualBytes);
  1099. }
  1100. finally
  1101. {
  1102. if (client.Exists(remoteFile))
  1103. {
  1104. client.DeleteFile(remoteFile);
  1105. }
  1106. }
  1107. }
  1108. }
  1109. [TestMethod]
  1110. public void Sftp_DownloadFile_FileDoesNotExist()
  1111. {
  1112. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1113. {
  1114. client.Connect();
  1115. var remoteFile = GenerateUniqueRemoteFileName();
  1116. if (client.Exists(remoteFile))
  1117. {
  1118. client.DeleteFile(remoteFile);
  1119. }
  1120. using (var ms = new MemoryStream())
  1121. {
  1122. try
  1123. {
  1124. client.DownloadFile(remoteFile, ms);
  1125. Assert.Fail();
  1126. }
  1127. catch (SftpPathNotFoundException ex)
  1128. {
  1129. Assert.IsNull(ex.InnerException);
  1130. Assert.AreEqual("No such file", ex.Message);
  1131. // ensure file was not created by us
  1132. Assert.IsFalse(client.Exists(remoteFile));
  1133. }
  1134. finally
  1135. {
  1136. if (client.Exists(remoteFile))
  1137. {
  1138. client.DeleteFile(remoteFile);
  1139. }
  1140. }
  1141. }
  1142. }
  1143. }
  1144. [TestMethod]
  1145. public void Sftp_ReadAllBytes_FileDoesNotExist()
  1146. {
  1147. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1148. {
  1149. client.Connect();
  1150. var remoteFile = GenerateUniqueRemoteFileName();
  1151. if (client.Exists(remoteFile))
  1152. {
  1153. client.DeleteFile(remoteFile);
  1154. }
  1155. try
  1156. {
  1157. client.ReadAllBytes(remoteFile);
  1158. Assert.Fail();
  1159. }
  1160. catch (SftpPathNotFoundException ex)
  1161. {
  1162. Assert.IsNull(ex.InnerException);
  1163. Assert.AreEqual("No such file", ex.Message);
  1164. // ensure file was not created by us
  1165. Assert.IsFalse(client.Exists(remoteFile));
  1166. }
  1167. finally
  1168. {
  1169. if (client.Exists(remoteFile))
  1170. {
  1171. client.DeleteFile(remoteFile);
  1172. }
  1173. }
  1174. }
  1175. }
  1176. [TestMethod]
  1177. public void Sftp_ReadAllLines_NoEncoding_ExistingFile()
  1178. {
  1179. var encoding = new UTF8Encoding(false, true);
  1180. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1181. var linesBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, lines) + Environment.NewLine,
  1182. encoding);
  1183. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1184. {
  1185. client.Connect();
  1186. var remoteFile = GenerateUniqueRemoteFileName();
  1187. if (client.Exists(remoteFile))
  1188. {
  1189. client.DeleteFile(remoteFile);
  1190. }
  1191. try
  1192. {
  1193. using (var sw = client.AppendText(remoteFile))
  1194. {
  1195. for (var i = 0; i < lines.Length; i++)
  1196. {
  1197. sw.WriteLine(lines[i]);
  1198. }
  1199. }
  1200. var actualLines = client.ReadAllLines(remoteFile);
  1201. Assert.IsNotNull(actualLines);
  1202. CollectionAssert.AreEqual(lines, actualLines);
  1203. var actualBytes = client.ReadAllBytes(remoteFile);
  1204. CollectionAssert.AreEqual(linesBytes, actualBytes);
  1205. }
  1206. finally
  1207. {
  1208. if (client.Exists(remoteFile))
  1209. {
  1210. client.DeleteFile(remoteFile);
  1211. }
  1212. }
  1213. }
  1214. }
  1215. [TestMethod]
  1216. public void Sftp_ReadAllLines_NoEncoding_FileDoesNotExist()
  1217. {
  1218. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1219. {
  1220. client.Connect();
  1221. var remoteFile = GenerateUniqueRemoteFileName();
  1222. if (client.Exists(remoteFile))
  1223. {
  1224. client.DeleteFile(remoteFile);
  1225. }
  1226. try
  1227. {
  1228. client.ReadAllLines(remoteFile);
  1229. Assert.Fail();
  1230. }
  1231. catch (SftpPathNotFoundException ex)
  1232. {
  1233. Assert.IsNull(ex.InnerException);
  1234. Assert.AreEqual("No such file", ex.Message);
  1235. // ensure file was not created by us
  1236. Assert.IsFalse(client.Exists(remoteFile));
  1237. }
  1238. finally
  1239. {
  1240. if (client.Exists(remoteFile))
  1241. {
  1242. client.DeleteFile(remoteFile);
  1243. }
  1244. }
  1245. }
  1246. }
  1247. [TestMethod]
  1248. public void Sftp_ReadAllLines_Encoding_ExistingFile()
  1249. {
  1250. var encoding = GetRandomEncoding();
  1251. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1252. var linesBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, lines) + Environment.NewLine,
  1253. encoding);
  1254. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1255. {
  1256. client.Connect();
  1257. var remoteFile = GenerateUniqueRemoteFileName();
  1258. if (client.Exists(remoteFile))
  1259. {
  1260. client.DeleteFile(remoteFile);
  1261. }
  1262. try
  1263. {
  1264. using (var sw = client.AppendText(remoteFile, encoding))
  1265. {
  1266. for (var i = 0; i < lines.Length; i++)
  1267. {
  1268. sw.WriteLine(lines[i]);
  1269. }
  1270. }
  1271. var actualLines = client.ReadAllLines(remoteFile, encoding);
  1272. Assert.IsNotNull(actualLines);
  1273. CollectionAssert.AreEqual(lines, actualLines);
  1274. var actualBytes = client.ReadAllBytes(remoteFile);
  1275. CollectionAssert.AreEqual(linesBytes, actualBytes);
  1276. }
  1277. finally
  1278. {
  1279. if (client.Exists(remoteFile))
  1280. {
  1281. client.DeleteFile(remoteFile);
  1282. }
  1283. }
  1284. }
  1285. }
  1286. [TestMethod]
  1287. public void Sftp_ReadAllLines_Encoding_FileDoesNotExist()
  1288. {
  1289. var encoding = GetRandomEncoding();
  1290. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1291. {
  1292. client.Connect();
  1293. var remoteFile = GenerateUniqueRemoteFileName();
  1294. if (client.Exists(remoteFile))
  1295. {
  1296. client.DeleteFile(remoteFile);
  1297. }
  1298. try
  1299. {
  1300. client.ReadAllLines(remoteFile, encoding);
  1301. Assert.Fail();
  1302. }
  1303. catch (SftpPathNotFoundException ex)
  1304. {
  1305. Assert.IsNull(ex.InnerException);
  1306. Assert.AreEqual("No such file", ex.Message);
  1307. // ensure file was not created by us
  1308. Assert.IsFalse(client.Exists(remoteFile));
  1309. }
  1310. finally
  1311. {
  1312. if (client.Exists(remoteFile))
  1313. {
  1314. client.DeleteFile(remoteFile);
  1315. }
  1316. }
  1317. }
  1318. }
  1319. [TestMethod]
  1320. public void Sftp_ReadAllText_NoEncoding_ExistingFile()
  1321. {
  1322. var encoding = new UTF8Encoding(false, true);
  1323. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1324. var expectedText = string.Join(Environment.NewLine, lines) + Environment.NewLine;
  1325. var expectedBytes = GetBytesWithPreamble(expectedText, encoding);
  1326. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1327. {
  1328. client.Connect();
  1329. var remoteFile = GenerateUniqueRemoteFileName();
  1330. if (client.Exists(remoteFile))
  1331. {
  1332. client.DeleteFile(remoteFile);
  1333. }
  1334. try
  1335. {
  1336. using (var sw = client.AppendText(remoteFile))
  1337. {
  1338. for (var i = 0; i < lines.Length; i++)
  1339. {
  1340. sw.WriteLine(lines[i]);
  1341. }
  1342. }
  1343. var actualText = client.ReadAllText(remoteFile);
  1344. Assert.AreEqual(expectedText, actualText);
  1345. var actualBytes = client.ReadAllBytes(remoteFile);
  1346. CollectionAssert.AreEqual(expectedBytes, actualBytes);
  1347. }
  1348. finally
  1349. {
  1350. if (client.Exists(remoteFile))
  1351. {
  1352. client.DeleteFile(remoteFile);
  1353. }
  1354. }
  1355. }
  1356. }
  1357. [TestMethod]
  1358. public void Sftp_ReadAllText_NoEncoding_FileDoesNotExist()
  1359. {
  1360. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1361. {
  1362. client.Connect();
  1363. var remoteFile = GenerateUniqueRemoteFileName();
  1364. if (client.Exists(remoteFile))
  1365. {
  1366. client.DeleteFile(remoteFile);
  1367. }
  1368. try
  1369. {
  1370. client.ReadAllText(remoteFile);
  1371. Assert.Fail();
  1372. }
  1373. catch (SftpPathNotFoundException ex)
  1374. {
  1375. Assert.IsNull(ex.InnerException);
  1376. Assert.AreEqual("No such file", ex.Message);
  1377. // ensure file was not created by us
  1378. Assert.IsFalse(client.Exists(remoteFile));
  1379. }
  1380. finally
  1381. {
  1382. if (client.Exists(remoteFile))
  1383. {
  1384. client.DeleteFile(remoteFile);
  1385. }
  1386. }
  1387. }
  1388. }
  1389. [TestMethod]
  1390. public void Sftp_ReadAllText_Encoding_ExistingFile()
  1391. {
  1392. var encoding = GetRandomEncoding();
  1393. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1394. var expectedText = string.Join(Environment.NewLine, lines) + Environment.NewLine;
  1395. var expectedBytes = GetBytesWithPreamble(expectedText, encoding);
  1396. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1397. {
  1398. client.Connect();
  1399. var remoteFile = GenerateUniqueRemoteFileName();
  1400. if (client.Exists(remoteFile))
  1401. {
  1402. client.DeleteFile(remoteFile);
  1403. }
  1404. try
  1405. {
  1406. using (var sw = client.AppendText(remoteFile, encoding))
  1407. {
  1408. for (var i = 0; i < lines.Length; i++)
  1409. {
  1410. sw.WriteLine(lines[i]);
  1411. }
  1412. }
  1413. var actualText = client.ReadAllText(remoteFile, encoding);
  1414. Assert.AreEqual(expectedText, actualText);
  1415. var actualBytes = client.ReadAllBytes(remoteFile);
  1416. CollectionAssert.AreEqual(expectedBytes, actualBytes);
  1417. }
  1418. finally
  1419. {
  1420. if (client.Exists(remoteFile))
  1421. {
  1422. client.DeleteFile(remoteFile);
  1423. }
  1424. }
  1425. }
  1426. }
  1427. [TestMethod]
  1428. public void Sftp_ReadAllText_Encoding_FileDoesNotExist()
  1429. {
  1430. var encoding = GetRandomEncoding();
  1431. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1432. {
  1433. client.Connect();
  1434. var remoteFile = GenerateUniqueRemoteFileName();
  1435. if (client.Exists(remoteFile))
  1436. {
  1437. client.DeleteFile(remoteFile);
  1438. }
  1439. try
  1440. {
  1441. client.ReadAllText(remoteFile, encoding);
  1442. Assert.Fail();
  1443. }
  1444. catch (SftpPathNotFoundException ex)
  1445. {
  1446. Assert.IsNull(ex.InnerException);
  1447. Assert.AreEqual("No such file", ex.Message);
  1448. // ensure file was not created by us
  1449. Assert.IsFalse(client.Exists(remoteFile));
  1450. }
  1451. finally
  1452. {
  1453. if (client.Exists(remoteFile))
  1454. {
  1455. client.DeleteFile(remoteFile);
  1456. }
  1457. }
  1458. }
  1459. }
  1460. [TestMethod]
  1461. public void Sftp_ReadLines_NoEncoding_ExistingFile()
  1462. {
  1463. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1464. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1465. {
  1466. client.Connect();
  1467. var remoteFile = GenerateUniqueRemoteFileName();
  1468. if (client.Exists(remoteFile))
  1469. {
  1470. client.DeleteFile(remoteFile);
  1471. }
  1472. try
  1473. {
  1474. using (var sw = client.AppendText(remoteFile))
  1475. {
  1476. for (var i = 0; i < lines.Length; i++)
  1477. {
  1478. sw.WriteLine(lines[i]);
  1479. }
  1480. }
  1481. var actualLines = client.ReadLines(remoteFile);
  1482. Assert.IsNotNull(actualLines);
  1483. // These two lines together test double enumeration.
  1484. Assert.AreEqual(lines[0], actualLines.First());
  1485. CollectionAssert.AreEqual(lines, actualLines.ToArray());
  1486. }
  1487. finally
  1488. {
  1489. if (client.Exists(remoteFile))
  1490. {
  1491. client.DeleteFile(remoteFile);
  1492. }
  1493. }
  1494. }
  1495. }
  1496. [TestMethod]
  1497. [DataRow(false)]
  1498. [DataRow(true)]
  1499. public void Sftp_ReadLines_FileDoesNotExist(bool encoding)
  1500. {
  1501. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1502. {
  1503. client.Connect();
  1504. var remoteFile = GenerateUniqueRemoteFileName();
  1505. if (client.Exists(remoteFile))
  1506. {
  1507. client.DeleteFile(remoteFile);
  1508. }
  1509. // This exception should bubble up immediately
  1510. var nullEx = encoding
  1511. ? Assert.Throws<ArgumentNullException>(() => client.ReadLines(null, GetRandomEncoding()))
  1512. : Assert.Throws<ArgumentNullException>(() => client.ReadLines(null));
  1513. Assert.AreEqual("path", nullEx.ParamName);
  1514. try
  1515. {
  1516. var ex = Assert.ThrowsExactly<SftpPathNotFoundException>(() =>
  1517. {
  1518. // The PathNotFound exception is permitted to bubble up only upon
  1519. // enumerating.
  1520. var lines = encoding
  1521. ? client.ReadLines(remoteFile, GetRandomEncoding())
  1522. : client.ReadLines(remoteFile);
  1523. using var enumerator = lines.GetEnumerator();
  1524. _ = enumerator.MoveNext();
  1525. });
  1526. Assert.IsNull(ex.InnerException);
  1527. Assert.AreEqual("No such file", ex.Message);
  1528. // ensure file was not created by us
  1529. Assert.IsFalse(client.Exists(remoteFile));
  1530. }
  1531. finally
  1532. {
  1533. if (client.Exists(remoteFile))
  1534. {
  1535. client.DeleteFile(remoteFile);
  1536. }
  1537. }
  1538. }
  1539. }
  1540. [TestMethod]
  1541. public void Sftp_ReadLines_Encoding_ExistingFile()
  1542. {
  1543. var encoding = GetRandomEncoding();
  1544. var lines = new[] { "\u0100ert & Ann", "Forever", "&", "\u0116ver" };
  1545. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1546. {
  1547. client.Connect();
  1548. var remoteFile = GenerateUniqueRemoteFileName();
  1549. if (client.Exists(remoteFile))
  1550. {
  1551. client.DeleteFile(remoteFile);
  1552. }
  1553. try
  1554. {
  1555. using (var sw = client.AppendText(remoteFile, encoding))
  1556. {
  1557. for (var i = 0; i < lines.Length; i++)
  1558. {
  1559. sw.WriteLine(lines[i]);
  1560. }
  1561. }
  1562. var actualLines = client.ReadLines(remoteFile, encoding);
  1563. Assert.IsNotNull(actualLines);
  1564. // These two lines together test double enumeration.
  1565. Assert.AreEqual(lines[0], actualLines.First());
  1566. CollectionAssert.AreEqual(lines, actualLines.ToArray());
  1567. }
  1568. finally
  1569. {
  1570. if (client.Exists(remoteFile))
  1571. {
  1572. client.DeleteFile(remoteFile);
  1573. }
  1574. }
  1575. }
  1576. }
  1577. [TestMethod]
  1578. public void Sftp_WriteAllBytes_DirectoryDoesNotExist()
  1579. {
  1580. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1581. var content = GenerateRandom(size: 5);
  1582. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1583. {
  1584. client.Connect();
  1585. if (client.Exists(remoteFile))
  1586. {
  1587. client.DeleteFile(remoteFile);
  1588. }
  1589. try
  1590. {
  1591. client.WriteAllBytes(remoteFile, content);
  1592. Assert.Fail();
  1593. }
  1594. catch (SftpPathNotFoundException ex)
  1595. {
  1596. Assert.IsNull(ex.InnerException);
  1597. Assert.AreEqual("No such file", ex.Message);
  1598. }
  1599. finally
  1600. {
  1601. if (client.Exists(remoteFile))
  1602. {
  1603. client.DeleteFile(remoteFile);
  1604. }
  1605. }
  1606. }
  1607. }
  1608. [TestMethod]
  1609. public void Sftp_WriteAllBytes_ExistingFile()
  1610. {
  1611. var initialContent = GenerateRandom(size: 13);
  1612. var newContent1 = GenerateRandom(size: 5);
  1613. var newContent2 = GenerateRandom(size: 50000);
  1614. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1615. {
  1616. client.Connect();
  1617. var remoteFile = GenerateUniqueRemoteFileName();
  1618. if (client.Exists(remoteFile))
  1619. {
  1620. client.DeleteFile(remoteFile);
  1621. }
  1622. try
  1623. {
  1624. using (var fs = client.Create(remoteFile))
  1625. {
  1626. fs.Write(initialContent, offset: 0, initialContent.Length);
  1627. }
  1628. #region Write less bytes than the current content, overwriting that content
  1629. client.WriteAllBytes(remoteFile, newContent1);
  1630. var actualContent1 = client.ReadAllBytes(remoteFile);
  1631. CollectionAssert.AreEqual(newContent1, actualContent1);
  1632. #endregion
  1633. #region Write more bytes than the current content, overwriting and appending to that content
  1634. client.WriteAllBytes(remoteFile, newContent2);
  1635. var actualContent2 = client.ReadAllBytes(remoteFile);
  1636. CollectionAssert.AreEqual(newContent2, actualContent2);
  1637. #endregion
  1638. }
  1639. finally
  1640. {
  1641. if (client.Exists(remoteFile))
  1642. {
  1643. client.DeleteFile(remoteFile);
  1644. }
  1645. }
  1646. }
  1647. }
  1648. [TestMethod]
  1649. public void Sftp_WriteAllBytes_FileDoesNotExist()
  1650. {
  1651. var content = GenerateRandom(size: 13);
  1652. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1653. {
  1654. client.Connect();
  1655. var remoteFile = GenerateUniqueRemoteFileName();
  1656. if (client.Exists(remoteFile))
  1657. {
  1658. client.DeleteFile(remoteFile);
  1659. }
  1660. try
  1661. {
  1662. client.WriteAllBytes(remoteFile, content);
  1663. var actualContent1 = client.ReadAllBytes(remoteFile);
  1664. CollectionAssert.AreEqual(content, actualContent1);
  1665. }
  1666. finally
  1667. {
  1668. if (client.Exists(remoteFile))
  1669. {
  1670. client.DeleteFile(remoteFile);
  1671. }
  1672. }
  1673. }
  1674. }
  1675. [TestMethod]
  1676. public void Sftp_WriteAllLines_IEnumerable_NoEncoding_DirectoryDoesNotExist()
  1677. {
  1678. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1679. IEnumerable<string> linesToWrite = new[] { "Forever", "&", "\u0116ver" };
  1680. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1681. {
  1682. client.Connect();
  1683. if (client.Exists(remoteFile))
  1684. {
  1685. client.DeleteFile(remoteFile);
  1686. }
  1687. try
  1688. {
  1689. client.WriteAllLines(remoteFile, linesToWrite);
  1690. Assert.Fail();
  1691. }
  1692. catch (SftpPathNotFoundException ex)
  1693. {
  1694. Assert.IsNull(ex.InnerException);
  1695. Assert.AreEqual("No such file", ex.Message);
  1696. }
  1697. finally
  1698. {
  1699. if (client.Exists(remoteFile))
  1700. {
  1701. client.DeleteFile(remoteFile);
  1702. }
  1703. }
  1704. }
  1705. }
  1706. [TestMethod]
  1707. public void Sftp_WriteAllLines_IEnumerable_NoEncoding_ExistingFile()
  1708. {
  1709. var encoding = new UTF8Encoding(false, true);
  1710. var initialContent = "\u0100ert & Ann Forever & Ever Lisa & Sofie";
  1711. IEnumerable<string> linesToWrite1 = new[] { "Forever", "&", "\u0116ver" };
  1712. var linesToWrite1Bytes =
  1713. GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite1) + Environment.NewLine, encoding);
  1714. IEnumerable<string> linesToWrite2 = new[] { "Forever", "&", "\u0116ver", "Gert & Ann", "Lisa + Sofie" };
  1715. var linesToWrite2Bytes =
  1716. GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite2) + Environment.NewLine, encoding);
  1717. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1718. {
  1719. client.Connect();
  1720. var remoteFile = GenerateUniqueRemoteFileName();
  1721. if (client.Exists(remoteFile))
  1722. {
  1723. client.DeleteFile(remoteFile);
  1724. }
  1725. try
  1726. {
  1727. // create initial content
  1728. client.WriteAllText(remoteFile, initialContent);
  1729. #region Write less bytes than the current content, overwriting that content
  1730. client.WriteAllLines(remoteFile, linesToWrite1);
  1731. var actualBytes = client.ReadAllBytes(remoteFile);
  1732. CollectionAssert.AreEqual(linesToWrite1Bytes, actualBytes);
  1733. #endregion
  1734. #region Write more bytes than the current content, overwriting and appending to that content
  1735. client.WriteAllLines(remoteFile, linesToWrite2);
  1736. actualBytes = client.ReadAllBytes(remoteFile);
  1737. CollectionAssert.AreEqual(linesToWrite2Bytes, actualBytes);
  1738. #endregion Write more bytes than the current content, overwriting and appending to that content
  1739. }
  1740. finally
  1741. {
  1742. if (client.Exists(remoteFile))
  1743. {
  1744. client.DeleteFile(remoteFile);
  1745. }
  1746. }
  1747. }
  1748. }
  1749. [TestMethod]
  1750. public void Sftp_WriteAllLines_IEnumerable_NoEncoding_FileDoesNotExist()
  1751. {
  1752. var encoding = new UTF8Encoding(false, true);
  1753. IEnumerable<string> linesToWrite = new[] { "\u0139isa", "&", "Sofie" };
  1754. var linesToWriteBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite) + Environment.NewLine, encoding);
  1755. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1756. {
  1757. client.Connect();
  1758. var remoteFile = GenerateUniqueRemoteFileName();
  1759. if (client.Exists(remoteFile))
  1760. {
  1761. client.DeleteFile(remoteFile);
  1762. }
  1763. try
  1764. {
  1765. client.WriteAllLines(remoteFile, linesToWrite);
  1766. var actualBytes = client.ReadAllBytes(remoteFile);
  1767. CollectionAssert.AreEqual(linesToWriteBytes, actualBytes);
  1768. }
  1769. finally
  1770. {
  1771. if (client.Exists(remoteFile))
  1772. {
  1773. client.DeleteFile(remoteFile);
  1774. }
  1775. }
  1776. }
  1777. }
  1778. [TestMethod]
  1779. public void Sftp_WriteAllLines_IEnumerable_Encoding_DirectoryDoesNotExist()
  1780. {
  1781. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1782. var encoding = GetRandomEncoding();
  1783. IEnumerable<string> linesToWrite = new[] { "Forever", "&", "\u0116ver" };
  1784. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1785. {
  1786. client.Connect();
  1787. if (client.Exists(remoteFile))
  1788. {
  1789. client.DeleteFile(remoteFile);
  1790. }
  1791. try
  1792. {
  1793. client.WriteAllLines(remoteFile, linesToWrite, encoding);
  1794. Assert.Fail();
  1795. }
  1796. catch (SftpPathNotFoundException ex)
  1797. {
  1798. Assert.IsNull(ex.InnerException);
  1799. Assert.AreEqual("No such file", ex.Message);
  1800. }
  1801. finally
  1802. {
  1803. if (client.Exists(remoteFile))
  1804. {
  1805. client.DeleteFile(remoteFile);
  1806. }
  1807. }
  1808. }
  1809. }
  1810. [TestMethod]
  1811. public void Sftp_WriteAllLines_IEnumerable_Encoding_ExistingFile()
  1812. {
  1813. var encoding = GetRandomEncoding();
  1814. const string initialContent = "\u0100ert & Ann Forever & Ever Lisa & Sofie";
  1815. IEnumerable<string> linesToWrite1 = new[] { "Forever", "&", "\u0116ver" };
  1816. var linesToWrite1Bytes =
  1817. GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite1) + Environment.NewLine, encoding);
  1818. IEnumerable<string> linesToWrite2 = new[] { "Forever", "&", "\u0116ver", "Gert & Ann", "Lisa + Sofie" };
  1819. var linesToWrite2Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite2) + Environment.NewLine, encoding);
  1820. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1821. {
  1822. client.Connect();
  1823. var remoteFile = GenerateUniqueRemoteFileName();
  1824. if (client.Exists(remoteFile))
  1825. {
  1826. client.DeleteFile(remoteFile);
  1827. }
  1828. try
  1829. {
  1830. // create initial content
  1831. client.WriteAllText(remoteFile, initialContent, encoding);
  1832. #region Write less bytes than the current content, overwriting that content
  1833. client.WriteAllLines(remoteFile, linesToWrite1, encoding);
  1834. var actualBytes = client.ReadAllBytes(remoteFile);
  1835. CollectionAssert.AreEqual(linesToWrite1Bytes, actualBytes);
  1836. #endregion
  1837. #region Write more bytes than the current content, overwriting and appending to that content
  1838. client.WriteAllLines(remoteFile, linesToWrite2, encoding);
  1839. actualBytes = client.ReadAllBytes(remoteFile);
  1840. CollectionAssert.AreEqual(linesToWrite2Bytes, actualBytes);
  1841. #endregion Write more bytes than the current content, overwriting and appending to that content
  1842. }
  1843. finally
  1844. {
  1845. if (client.Exists(remoteFile))
  1846. {
  1847. client.DeleteFile(remoteFile);
  1848. }
  1849. }
  1850. }
  1851. }
  1852. [TestMethod]
  1853. public void Sftp_WriteAllLines_IEnumerable_Encoding_FileDoesNotExist()
  1854. {
  1855. var encoding = GetRandomEncoding();
  1856. IEnumerable<string> linesToWrite = new[] { "\u0139isa", "&", "Sofie" };
  1857. var linesToWriteBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite) + Environment.NewLine, encoding);
  1858. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1859. {
  1860. client.Connect();
  1861. var remoteFile = GenerateUniqueRemoteFileName();
  1862. if (client.Exists(remoteFile))
  1863. {
  1864. client.DeleteFile(remoteFile);
  1865. }
  1866. try
  1867. {
  1868. client.WriteAllLines(remoteFile, linesToWrite, encoding);
  1869. var actualBytes = client.ReadAllBytes(remoteFile);
  1870. CollectionAssert.AreEqual(linesToWriteBytes, actualBytes);
  1871. }
  1872. finally
  1873. {
  1874. if (client.Exists(remoteFile))
  1875. {
  1876. client.DeleteFile(remoteFile);
  1877. }
  1878. }
  1879. }
  1880. }
  1881. [TestMethod]
  1882. public void Sftp_WriteAllLines_Array_NoEncoding_DirectoryDoesNotExist()
  1883. {
  1884. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1885. var linesToWrite = new[] { "Forever", "&", "\u0116ver" };
  1886. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1887. {
  1888. client.Connect();
  1889. if (client.Exists(remoteFile))
  1890. {
  1891. client.DeleteFile(remoteFile);
  1892. }
  1893. try
  1894. {
  1895. client.WriteAllLines(remoteFile, linesToWrite);
  1896. Assert.Fail();
  1897. }
  1898. catch (SftpPathNotFoundException ex)
  1899. {
  1900. Assert.IsNull(ex.InnerException);
  1901. Assert.AreEqual("No such file", ex.Message);
  1902. }
  1903. finally
  1904. {
  1905. if (client.Exists(remoteFile))
  1906. {
  1907. client.DeleteFile(remoteFile);
  1908. }
  1909. }
  1910. }
  1911. }
  1912. [TestMethod]
  1913. public void Sftp_WriteAllLines_Array_NoEncoding_ExistingFile()
  1914. {
  1915. var encoding = new UTF8Encoding(false, true);
  1916. const string initialContent = "\u0100ert & Ann Forever & Ever Lisa & Sofie";
  1917. var linesToWrite1 = new[] { "Forever", "&", "\u0116ver" };
  1918. var linesToWrite1Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite1) + Environment.NewLine, encoding);
  1919. var linesToWrite2 = new[] { "Forever", "&", "\u0116ver", "Gert & Ann", "Lisa + Sofie" };
  1920. var linesToWrite2Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite2) + Environment.NewLine, encoding);
  1921. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1922. {
  1923. client.Connect();
  1924. var remoteFile = GenerateUniqueRemoteFileName();
  1925. if (client.Exists(remoteFile))
  1926. {
  1927. client.DeleteFile(remoteFile);
  1928. }
  1929. try
  1930. {
  1931. // create initial content
  1932. client.WriteAllText(remoteFile, initialContent);
  1933. #region Write less bytes than the current content, overwriting that content
  1934. client.WriteAllLines(remoteFile, linesToWrite1);
  1935. var actualBytes = client.ReadAllBytes(remoteFile);
  1936. CollectionAssert.AreEqual(linesToWrite1Bytes, actualBytes);
  1937. #endregion
  1938. #region Write more bytes than the current content, overwriting and appending to that content
  1939. client.WriteAllLines(remoteFile, linesToWrite2);
  1940. actualBytes = client.ReadAllBytes(remoteFile);
  1941. CollectionAssert.AreEqual(linesToWrite2Bytes, actualBytes);
  1942. #endregion Write more bytes than the current content, overwriting and appending to that content
  1943. }
  1944. finally
  1945. {
  1946. if (client.Exists(remoteFile))
  1947. {
  1948. client.DeleteFile(remoteFile);
  1949. }
  1950. }
  1951. }
  1952. }
  1953. [TestMethod]
  1954. public void Sftp_WriteAllLines_Array_NoEncoding_FileDoesNotExist()
  1955. {
  1956. var encoding = new UTF8Encoding(false, true);
  1957. var linesToWrite = new[] { "\u0139isa", "&", "Sofie" };
  1958. var linesToWriteBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite) + Environment.NewLine, encoding);
  1959. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1960. {
  1961. client.Connect();
  1962. var remoteFile = GenerateUniqueRemoteFileName();
  1963. if (client.Exists(remoteFile))
  1964. {
  1965. client.DeleteFile(remoteFile);
  1966. }
  1967. try
  1968. {
  1969. client.WriteAllLines(remoteFile, linesToWrite);
  1970. var actualBytes = client.ReadAllBytes(remoteFile);
  1971. CollectionAssert.AreEqual(linesToWriteBytes, actualBytes);
  1972. }
  1973. finally
  1974. {
  1975. if (client.Exists(remoteFile))
  1976. {
  1977. client.DeleteFile(remoteFile);
  1978. }
  1979. }
  1980. }
  1981. }
  1982. [TestMethod]
  1983. public void Sftp_WriteAllLines_Array_Encoding_DirectoryDoesNotExist()
  1984. {
  1985. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  1986. var encoding = GetRandomEncoding();
  1987. var linesToWrite = new[] { "Forever", "&", "\u0116ver" };
  1988. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  1989. {
  1990. client.Connect();
  1991. if (client.Exists(remoteFile))
  1992. {
  1993. client.DeleteFile(remoteFile);
  1994. }
  1995. try
  1996. {
  1997. client.WriteAllLines(remoteFile, linesToWrite, encoding);
  1998. Assert.Fail();
  1999. }
  2000. catch (SftpPathNotFoundException ex)
  2001. {
  2002. Assert.IsNull(ex.InnerException);
  2003. Assert.AreEqual("No such file", ex.Message);
  2004. }
  2005. finally
  2006. {
  2007. if (client.Exists(remoteFile))
  2008. {
  2009. client.DeleteFile(remoteFile);
  2010. }
  2011. }
  2012. }
  2013. }
  2014. [TestMethod]
  2015. public void Sftp_WriteAllLines_Array_Encoding_ExistingFile()
  2016. {
  2017. const string initialContent = "\u0100ert & Ann Forever & Ever Lisa & Sofie";
  2018. var encoding = GetRandomEncoding();
  2019. var linesToWrite1 = new[] { "Forever", "&", "\u0116ver" };
  2020. var linesToWrite1Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite1) + Environment.NewLine, encoding);
  2021. var linesToWrite2 = new[] { "Forever", "&", "\u0116ver", "Gert & Ann", "Lisa + Sofie" };
  2022. var linesToWrite2Bytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite2) + Environment.NewLine, encoding);
  2023. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2024. {
  2025. client.Connect();
  2026. var remoteFile = GenerateUniqueRemoteFileName();
  2027. if (client.Exists(remoteFile))
  2028. {
  2029. client.DeleteFile(remoteFile);
  2030. }
  2031. try
  2032. {
  2033. // create initial content
  2034. client.WriteAllText(remoteFile, initialContent, encoding);
  2035. #region Write less bytes than the current content, overwriting that content
  2036. client.WriteAllLines(remoteFile, linesToWrite1, encoding);
  2037. var actualBytes = client.ReadAllBytes(remoteFile);
  2038. CollectionAssert.AreEqual(linesToWrite1Bytes, actualBytes);
  2039. #endregion
  2040. #region Write more bytes than the current content, overwriting and appending to that content
  2041. client.WriteAllLines(remoteFile, linesToWrite2, encoding);
  2042. actualBytes = client.ReadAllBytes(remoteFile);
  2043. CollectionAssert.AreEqual(linesToWrite2Bytes, actualBytes);
  2044. #endregion
  2045. }
  2046. finally
  2047. {
  2048. if (client.Exists(remoteFile))
  2049. {
  2050. client.DeleteFile(remoteFile);
  2051. }
  2052. }
  2053. }
  2054. }
  2055. [TestMethod]
  2056. public void Sftp_WriteAllLines_Array_Encoding_FileDoesNotExist()
  2057. {
  2058. var encoding = GetRandomEncoding();
  2059. var linesToWrite = new[] { "\u0139isa", "&", "Sofie" };
  2060. var linesToWriteBytes = GetBytesWithPreamble(string.Join(Environment.NewLine, linesToWrite) + Environment.NewLine, encoding);
  2061. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2062. {
  2063. client.Connect();
  2064. var remoteFile = GenerateUniqueRemoteFileName();
  2065. if (client.Exists(remoteFile))
  2066. {
  2067. client.DeleteFile(remoteFile);
  2068. }
  2069. try
  2070. {
  2071. client.WriteAllLines(remoteFile, linesToWrite, encoding);
  2072. var actualBytes = client.ReadAllBytes(remoteFile);
  2073. CollectionAssert.AreEqual(linesToWriteBytes, actualBytes);
  2074. }
  2075. finally
  2076. {
  2077. if (client.Exists(remoteFile))
  2078. {
  2079. client.DeleteFile(remoteFile);
  2080. }
  2081. }
  2082. }
  2083. }
  2084. [TestMethod]
  2085. public void Sftp_WriteAllText_NoEncoding_DirectoryDoesNotExist()
  2086. {
  2087. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  2088. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2089. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2090. {
  2091. client.Connect();
  2092. if (client.Exists(remoteFile))
  2093. {
  2094. client.DeleteFile(remoteFile);
  2095. }
  2096. try
  2097. {
  2098. client.WriteAllText(remoteFile, initialContent);
  2099. Assert.Fail();
  2100. }
  2101. catch (SftpPathNotFoundException ex)
  2102. {
  2103. Assert.IsNull(ex.InnerException);
  2104. Assert.AreEqual("No such file", ex.Message);
  2105. }
  2106. finally
  2107. {
  2108. if (client.Exists(remoteFile))
  2109. {
  2110. client.DeleteFile(remoteFile);
  2111. }
  2112. }
  2113. }
  2114. }
  2115. [TestMethod]
  2116. public void Sftp_WriteAllText_NoEncoding_ExistingFile()
  2117. {
  2118. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2119. const string newContent1 = "For\u0116ver & Ever";
  2120. var encoding = new UTF8Encoding(false, true);
  2121. var newContent1Bytes = GetBytesWithPreamble(newContent1, encoding);
  2122. var newContent2 = "Sofie & Lisa For\u0116ver & Ever with \u0100ert & Ann";
  2123. var newContent2Bytes = GetBytesWithPreamble(newContent2, encoding);
  2124. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2125. {
  2126. client.Connect();
  2127. var remoteFile = GenerateUniqueRemoteFileName();
  2128. if (client.Exists(remoteFile))
  2129. {
  2130. client.DeleteFile(remoteFile);
  2131. }
  2132. try
  2133. {
  2134. client.WriteAllText(remoteFile, initialContent);
  2135. #region Write less bytes than the current content, overwriting that content
  2136. client.WriteAllText(remoteFile, newContent1);
  2137. var actualBytes = client.ReadAllBytes(remoteFile);
  2138. CollectionAssert.AreEqual(newContent1Bytes, actualBytes);
  2139. #endregion
  2140. #region Write more bytes than the current content, overwriting and appending to that content
  2141. client.WriteAllText(remoteFile, newContent2);
  2142. actualBytes = client.ReadAllBytes(remoteFile);
  2143. CollectionAssert.AreEqual(newContent2Bytes, actualBytes);
  2144. #endregion Write more bytes than the current content, overwriting and appending to that content
  2145. }
  2146. finally
  2147. {
  2148. if (client.Exists(remoteFile))
  2149. {
  2150. client.DeleteFile(remoteFile);
  2151. }
  2152. }
  2153. }
  2154. }
  2155. [TestMethod]
  2156. public void Sftp_WriteAllText_NoEncoding_FileDoesNotExist()
  2157. {
  2158. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2159. var encoding = new UTF8Encoding(false, true);
  2160. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2161. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2162. {
  2163. client.Connect();
  2164. var remoteFile = GenerateUniqueRemoteFileName();
  2165. if (client.Exists(remoteFile))
  2166. {
  2167. client.DeleteFile(remoteFile);
  2168. }
  2169. try
  2170. {
  2171. client.WriteAllText(remoteFile, initialContent);
  2172. var actualBytes = client.ReadAllBytes(remoteFile);
  2173. CollectionAssert.AreEqual(initialContentBytes, actualBytes);
  2174. }
  2175. finally
  2176. {
  2177. if (client.Exists(remoteFile))
  2178. {
  2179. client.DeleteFile(remoteFile);
  2180. }
  2181. }
  2182. }
  2183. }
  2184. [TestMethod]
  2185. public void Sftp_WriteAllText_Encoding_DirectoryDoesNotExist()
  2186. {
  2187. const string remoteFile = "/home/sshnet/directorydoesnotexist/test";
  2188. var encoding = GetRandomEncoding();
  2189. const string content = "For\u0116ver & Ever";
  2190. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2191. {
  2192. client.Connect();
  2193. if (client.Exists(remoteFile))
  2194. {
  2195. client.DeleteFile(remoteFile);
  2196. }
  2197. try
  2198. {
  2199. client.WriteAllText(remoteFile, content, encoding);
  2200. Assert.Fail();
  2201. }
  2202. catch (SftpPathNotFoundException ex)
  2203. {
  2204. Assert.IsNull(ex.InnerException);
  2205. Assert.AreEqual("No such file", ex.Message);
  2206. }
  2207. finally
  2208. {
  2209. if (client.Exists(remoteFile))
  2210. {
  2211. client.DeleteFile(remoteFile);
  2212. }
  2213. }
  2214. }
  2215. }
  2216. [TestMethod]
  2217. public void Sftp_WriteAllText_Encoding_ExistingFile()
  2218. {
  2219. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2220. const string newContent1 = "For\u0116ver & Ever";
  2221. const string newContent2 = "Sofie & Lisa For\u0116ver & Ever with \u0100ert & Ann";
  2222. var encoding = GetRandomEncoding();
  2223. var newContent1Bytes = GetBytesWithPreamble(newContent1, encoding);
  2224. var newContent2Bytes = GetBytesWithPreamble(newContent2, encoding);
  2225. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2226. {
  2227. client.Connect();
  2228. var remoteFile = GenerateUniqueRemoteFileName();
  2229. if (client.Exists(remoteFile))
  2230. {
  2231. client.DeleteFile(remoteFile);
  2232. }
  2233. try
  2234. {
  2235. client.WriteAllText(remoteFile, initialContent, encoding);
  2236. #region Write less bytes than the current content, overwriting that content
  2237. client.WriteAllText(remoteFile, newContent1, encoding);
  2238. var actualBytes = client.ReadAllBytes(remoteFile);
  2239. CollectionAssert.AreEqual(newContent1Bytes, actualBytes);
  2240. #endregion
  2241. #region Write more bytes than the current content, overwriting and appending to that content
  2242. client.WriteAllText(remoteFile, newContent2, encoding);
  2243. actualBytes = client.ReadAllBytes(remoteFile);
  2244. CollectionAssert.AreEqual(newContent2Bytes, actualBytes);
  2245. #endregion Write more bytes than the current content, overwriting and appending to that content
  2246. }
  2247. finally
  2248. {
  2249. if (client.Exists(remoteFile))
  2250. {
  2251. client.DeleteFile(remoteFile);
  2252. }
  2253. }
  2254. }
  2255. }
  2256. [TestMethod]
  2257. public void Sftp_WriteAllText_Encoding_FileDoesNotExist()
  2258. {
  2259. const string initialContent = "\u0100ert & Ann Forever & \u0116ver Lisa & Sofie";
  2260. var encoding = GetRandomEncoding();
  2261. var initialContentBytes = GetBytesWithPreamble(initialContent, encoding);
  2262. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2263. {
  2264. client.Connect();
  2265. var remoteFile = GenerateUniqueRemoteFileName();
  2266. if (client.Exists(remoteFile))
  2267. {
  2268. client.DeleteFile(remoteFile);
  2269. }
  2270. try
  2271. {
  2272. client.WriteAllText(remoteFile, initialContent, encoding);
  2273. var actualBytes = client.ReadAllBytes(remoteFile);
  2274. CollectionAssert.AreEqual(initialContentBytes, actualBytes);
  2275. }
  2276. finally
  2277. {
  2278. if (client.Exists(remoteFile))
  2279. {
  2280. client.DeleteFile(remoteFile);
  2281. }
  2282. }
  2283. }
  2284. }
  2285. [TestMethod]
  2286. public void Sftp_BeginDownloadFile_FileDoesNotExist()
  2287. {
  2288. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2289. {
  2290. client.Connect();
  2291. var remoteFile = GenerateUniqueRemoteFileName();
  2292. if (client.Exists(remoteFile))
  2293. {
  2294. client.DeleteFile(remoteFile);
  2295. }
  2296. try
  2297. {
  2298. using (var ms = new MemoryStream())
  2299. {
  2300. var asyncResult = client.BeginDownloadFile(remoteFile, ms);
  2301. try
  2302. {
  2303. client.EndDownloadFile(asyncResult);
  2304. Assert.Fail();
  2305. }
  2306. catch (SftpPathNotFoundException ex)
  2307. {
  2308. Assert.IsNull(ex.InnerException);
  2309. Assert.AreEqual("No such file", ex.Message);
  2310. // ensure file was not created by us
  2311. Assert.IsFalse(client.Exists(remoteFile));
  2312. }
  2313. }
  2314. }
  2315. finally
  2316. {
  2317. if (client.Exists(remoteFile))
  2318. {
  2319. client.DeleteFile(remoteFile);
  2320. }
  2321. }
  2322. }
  2323. }
  2324. [TestMethod]
  2325. public void Sftp_BeginListDirectory_DirectoryDoesNotExist()
  2326. {
  2327. const string remoteDirectory = "/home/sshnet/test123";
  2328. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2329. {
  2330. client.Connect();
  2331. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  2332. {
  2333. command.Execute();
  2334. }
  2335. }
  2336. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2337. {
  2338. client.Connect();
  2339. var asyncResult = client.BeginListDirectory(remoteDirectory, null, null);
  2340. try
  2341. {
  2342. client.EndListDirectory(asyncResult);
  2343. Assert.Fail();
  2344. }
  2345. catch (SftpPathNotFoundException ex)
  2346. {
  2347. Assert.IsNull(ex.InnerException);
  2348. Assert.AreEqual("No such file", ex.Message);
  2349. // ensure directory was not created by us
  2350. Assert.IsFalse(client.Exists(remoteDirectory));
  2351. }
  2352. }
  2353. }
  2354. [TestMethod]
  2355. public void Sftp_BeginUploadFile_InputAndPath_DirectoryDoesNotExist()
  2356. {
  2357. const int size = 50 * 1024 * 1024;
  2358. const string remoteDirectory = "/home/sshnet/test123";
  2359. const string remoteFile = remoteDirectory + "/test";
  2360. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2361. {
  2362. client.Connect();
  2363. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  2364. {
  2365. command.Execute();
  2366. }
  2367. }
  2368. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2369. {
  2370. client.Connect();
  2371. var memoryStream = CreateMemoryStream(size);
  2372. memoryStream.Position = 0;
  2373. var asyncResult = client.BeginUploadFile(memoryStream, remoteFile);
  2374. try
  2375. {
  2376. client.EndUploadFile(asyncResult);
  2377. Assert.Fail();
  2378. }
  2379. catch (SftpPathNotFoundException)
  2380. {
  2381. }
  2382. }
  2383. }
  2384. [TestMethod]
  2385. public void Sftp_BeginUploadFile_InputAndPath_FileDoesNotExist()
  2386. {
  2387. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2388. {
  2389. client.Connect();
  2390. var remoteFile = GenerateUniqueRemoteFileName();
  2391. if (client.Exists(remoteFile))
  2392. {
  2393. client.DeleteFile(remoteFile);
  2394. }
  2395. try
  2396. {
  2397. var uploadMemoryStream = new MemoryStream();
  2398. var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8);
  2399. sw.Write("Gert & Ann");
  2400. sw.Flush();
  2401. uploadMemoryStream.Position = 0;
  2402. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile);
  2403. client.EndUploadFile(asyncResult);
  2404. using (var downloadMemoryStream = new MemoryStream())
  2405. {
  2406. DownloadFileRandomMethod(client, remoteFile, downloadMemoryStream);
  2407. downloadMemoryStream.Position = 0;
  2408. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2409. {
  2410. var content = sr.ReadToEnd();
  2411. Assert.AreEqual("Gert & Ann", content);
  2412. }
  2413. }
  2414. }
  2415. finally
  2416. {
  2417. if (client.Exists(remoteFile))
  2418. {
  2419. client.DeleteFile(remoteFile);
  2420. }
  2421. }
  2422. }
  2423. }
  2424. [TestMethod]
  2425. public void Sftp_BeginUploadFile_InputAndPath_ExistingFile()
  2426. {
  2427. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2428. {
  2429. client.Connect();
  2430. var remoteFile = GenerateUniqueRemoteFileName();
  2431. if (client.Exists(remoteFile))
  2432. {
  2433. client.DeleteFile(remoteFile);
  2434. }
  2435. try
  2436. {
  2437. client.WriteAllText(remoteFile, "Gert & Ann & Lisa");
  2438. var uploadMemoryStream = new MemoryStream();
  2439. var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8);
  2440. sw.Write("Ann & Gert");
  2441. sw.Flush();
  2442. uploadMemoryStream.Position = 0;
  2443. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile);
  2444. client.EndUploadFile(asyncResult);
  2445. using (var downloadMemoryStream = new MemoryStream())
  2446. {
  2447. DownloadFileRandomMethod(client, remoteFile, downloadMemoryStream);
  2448. downloadMemoryStream.Position = 0;
  2449. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2450. {
  2451. var content = sr.ReadToEnd();
  2452. Assert.AreEqual("Ann & Gert", content);
  2453. }
  2454. }
  2455. }
  2456. finally
  2457. {
  2458. if (client.Exists(remoteFile))
  2459. {
  2460. client.DeleteFile(remoteFile);
  2461. }
  2462. }
  2463. }
  2464. }
  2465. [TestMethod]
  2466. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsFalse_DirectoryDoesNotExist()
  2467. {
  2468. const int size = 50 * 1024 * 1024;
  2469. const string remoteDirectory = "/home/sshnet/test123";
  2470. const string remoteFile = remoteDirectory + "/test";
  2471. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2472. {
  2473. client.Connect();
  2474. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  2475. {
  2476. command.Execute();
  2477. }
  2478. }
  2479. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2480. {
  2481. client.Connect();
  2482. var memoryStream = CreateMemoryStream(size);
  2483. memoryStream.Position = 0;
  2484. var asyncResult = client.BeginUploadFile(memoryStream, remoteFile, false, null, null);
  2485. try
  2486. {
  2487. client.EndUploadFile(asyncResult);
  2488. Assert.Fail();
  2489. }
  2490. catch (SftpPathNotFoundException)
  2491. {
  2492. }
  2493. }
  2494. }
  2495. [TestMethod]
  2496. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsFalse_FileDoesNotExist()
  2497. {
  2498. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2499. {
  2500. client.Connect();
  2501. var remoteFile = GenerateUniqueRemoteFileName();
  2502. if (client.Exists(remoteFile))
  2503. {
  2504. client.DeleteFile(remoteFile);
  2505. }
  2506. try
  2507. {
  2508. using (var uploadMemoryStream = new MemoryStream())
  2509. using (var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8))
  2510. {
  2511. sw.Write("Gert & Ann");
  2512. sw.Flush();
  2513. uploadMemoryStream.Position = 0;
  2514. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile, false, null, null);
  2515. client.EndUploadFile(asyncResult);
  2516. }
  2517. using (var downloadMemoryStream = new MemoryStream())
  2518. {
  2519. DownloadFileRandomMethod(client, remoteFile, downloadMemoryStream);
  2520. downloadMemoryStream.Position = 0;
  2521. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2522. {
  2523. var content = sr.ReadToEnd();
  2524. Assert.AreEqual("Gert & Ann", content);
  2525. }
  2526. }
  2527. }
  2528. finally
  2529. {
  2530. if (client.Exists(remoteFile))
  2531. {
  2532. client.DeleteFile(remoteFile);
  2533. }
  2534. }
  2535. }
  2536. }
  2537. [TestMethod]
  2538. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsFalse_ExistingFile()
  2539. {
  2540. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2541. {
  2542. client.Connect();
  2543. var remoteFile = GenerateUniqueRemoteFileName();
  2544. if (client.Exists(remoteFile))
  2545. {
  2546. client.DeleteFile(remoteFile);
  2547. }
  2548. try
  2549. {
  2550. client.WriteAllText(remoteFile, "Gert & Ann & Lisa");
  2551. var uploadMemoryStream = new MemoryStream();
  2552. var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8);
  2553. sw.Write("Ann & Gert");
  2554. sw.Flush();
  2555. uploadMemoryStream.Position = 0;
  2556. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile, false, null, null);
  2557. try
  2558. {
  2559. client.EndUploadFile(asyncResult);
  2560. Assert.Fail();
  2561. }
  2562. catch (SshException ex)
  2563. {
  2564. Assert.AreEqual(typeof(SshException), ex.GetType());
  2565. Assert.IsNull(ex.InnerException);
  2566. Assert.AreEqual("Failure", ex.Message);
  2567. }
  2568. }
  2569. finally
  2570. {
  2571. if (client.Exists(remoteFile))
  2572. {
  2573. client.DeleteFile(remoteFile);
  2574. }
  2575. }
  2576. }
  2577. }
  2578. [TestMethod]
  2579. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsTrue_DirectoryDoesNotExist()
  2580. {
  2581. const int size = 50 * 1024 * 1024;
  2582. const string remoteDirectory = "/home/sshnet/test123";
  2583. const string remoteFile = remoteDirectory + "/test";
  2584. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2585. {
  2586. client.Connect();
  2587. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  2588. {
  2589. command.Execute();
  2590. }
  2591. }
  2592. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2593. {
  2594. client.Connect();
  2595. var memoryStream = CreateMemoryStream(size);
  2596. memoryStream.Position = 0;
  2597. var asyncResult = client.BeginUploadFile(memoryStream, remoteFile, true, null, null);
  2598. try
  2599. {
  2600. client.EndUploadFile(asyncResult);
  2601. Assert.Fail();
  2602. }
  2603. catch (SftpPathNotFoundException)
  2604. {
  2605. }
  2606. }
  2607. }
  2608. [TestMethod]
  2609. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsTrue_FileDoesNotExist()
  2610. {
  2611. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2612. {
  2613. client.Connect();
  2614. var remoteFile = GenerateUniqueRemoteFileName();
  2615. if (client.Exists(remoteFile))
  2616. {
  2617. client.DeleteFile(remoteFile);
  2618. }
  2619. try
  2620. {
  2621. using (var uploadMemoryStream = new MemoryStream())
  2622. using (var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8))
  2623. {
  2624. sw.Write("Gert & Ann");
  2625. sw.Flush();
  2626. uploadMemoryStream.Position = 0;
  2627. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile, true, null, null);
  2628. client.EndUploadFile(asyncResult);
  2629. }
  2630. using (var downloadMemoryStream = new MemoryStream())
  2631. {
  2632. DownloadFileRandomMethod(client, remoteFile, downloadMemoryStream);
  2633. downloadMemoryStream.Position = 0;
  2634. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2635. {
  2636. var content = sr.ReadToEnd();
  2637. Assert.AreEqual("Gert & Ann", content);
  2638. }
  2639. }
  2640. }
  2641. finally
  2642. {
  2643. if (client.Exists(remoteFile))
  2644. {
  2645. client.DeleteFile(remoteFile);
  2646. }
  2647. }
  2648. }
  2649. }
  2650. [TestMethod]
  2651. public void Sftp_BeginUploadFile_InputAndPathAndCanOverride_CanOverrideIsTrue_ExistingFile()
  2652. {
  2653. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2654. {
  2655. client.Connect();
  2656. var remoteFile = GenerateUniqueRemoteFileName();
  2657. if (client.Exists(remoteFile))
  2658. {
  2659. client.DeleteFile(remoteFile);
  2660. }
  2661. try
  2662. {
  2663. client.WriteAllText(remoteFile, "Gert & Ann & Lisa");
  2664. using (var uploadMemoryStream = new MemoryStream())
  2665. using (var sw = new StreamWriter(uploadMemoryStream, Encoding.UTF8))
  2666. {
  2667. sw.Write("Ann & Gert");
  2668. sw.Flush();
  2669. uploadMemoryStream.Position = 0;
  2670. var asyncResult = client.BeginUploadFile(uploadMemoryStream, remoteFile, true, null, null);
  2671. client.EndUploadFile(asyncResult);
  2672. }
  2673. using (var downloadMemoryStream = new MemoryStream())
  2674. {
  2675. DownloadFileRandomMethod(client, remoteFile, downloadMemoryStream);
  2676. downloadMemoryStream.Position = 0;
  2677. using (var sr = new StreamReader(downloadMemoryStream, Encoding.UTF8))
  2678. {
  2679. var content = sr.ReadToEnd();
  2680. Assert.AreEqual("Ann & Gert", content);
  2681. }
  2682. }
  2683. }
  2684. finally
  2685. {
  2686. if (client.Exists(remoteFile))
  2687. {
  2688. client.DeleteFile(remoteFile);
  2689. }
  2690. }
  2691. }
  2692. }
  2693. [TestMethod]
  2694. public void Sftp_UploadAndDownloadBigFile()
  2695. {
  2696. const int size = 50 * 1024 * 1024;
  2697. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2698. {
  2699. client.Connect();
  2700. var remoteFile = GenerateUniqueRemoteFileName();
  2701. if (client.Exists(remoteFile))
  2702. {
  2703. client.Delete(remoteFile);
  2704. }
  2705. try
  2706. {
  2707. var memoryStream = CreateMemoryStream(size);
  2708. memoryStream.Position = 0;
  2709. var expectedHash = CreateHash(memoryStream);
  2710. memoryStream.Position = 0;
  2711. client.UploadFile(memoryStream, remoteFile);
  2712. memoryStream.SetLength(0);
  2713. var stopwatch = new Stopwatch();
  2714. stopwatch.Start();
  2715. client.DownloadFile(remoteFile, memoryStream);
  2716. stopwatch.Stop();
  2717. Assert.AreEqual(size, memoryStream.Length);
  2718. memoryStream.Position = 0;
  2719. var actualHash = CreateHash(memoryStream);
  2720. Assert.AreEqual(expectedHash, actualHash);
  2721. Console.WriteLine(@"Elapsed: {0} ms", stopwatch.ElapsedMilliseconds);
  2722. Console.WriteLine(@"Transfer speed: {0:N2} KB/s",
  2723. CalculateTransferSpeed(memoryStream.Length, stopwatch.ElapsedMilliseconds));
  2724. }
  2725. finally
  2726. {
  2727. if (client.Exists(remoteFile))
  2728. {
  2729. client.Delete(remoteFile);
  2730. }
  2731. }
  2732. }
  2733. }
  2734. /// <summary>
  2735. /// Issue 1672
  2736. /// </summary>
  2737. [TestMethod]
  2738. public void Sftp_CurrentWorkingDirectory()
  2739. {
  2740. const string homeDirectory = "/home/sshnet";
  2741. const string otherDirectory = homeDirectory + "/dir";
  2742. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2743. {
  2744. client.Connect();
  2745. if (client.Exists(otherDirectory))
  2746. {
  2747. client.DeleteDirectory(otherDirectory);
  2748. }
  2749. try
  2750. {
  2751. client.CreateDirectory(otherDirectory);
  2752. client.ChangeDirectory(otherDirectory);
  2753. using (var s = CreateStreamWithContent("A"))
  2754. {
  2755. client.UploadFile(s, "a.txt");
  2756. }
  2757. using (var s = new MemoryStream())
  2758. {
  2759. client.DownloadFile("a.txt", s);
  2760. s.Position = 0;
  2761. var content = Encoding.ASCII.GetString(s.ToArray());
  2762. Assert.AreEqual("A", content);
  2763. }
  2764. Assert.IsTrue(client.Exists(otherDirectory + "/a.txt"));
  2765. client.DeleteFile("a.txt");
  2766. Assert.IsFalse(client.Exists(otherDirectory + "/a.txt"));
  2767. client.DeleteDirectory(".");
  2768. Assert.IsFalse(client.Exists(otherDirectory));
  2769. }
  2770. finally
  2771. {
  2772. if (client.Exists(otherDirectory))
  2773. {
  2774. client.DeleteDirectory(otherDirectory);
  2775. }
  2776. }
  2777. }
  2778. }
  2779. [TestMethod]
  2780. public void Sftp_Exists()
  2781. {
  2782. const string remoteHome = "/home/sshnet";
  2783. #region Setup
  2784. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2785. {
  2786. client.Connect();
  2787. #region Clean-up
  2788. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/DoesNotExist"}"))
  2789. {
  2790. command.Execute();
  2791. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2792. }
  2793. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.directory.exists"}"))
  2794. {
  2795. command.Execute();
  2796. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2797. }
  2798. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/directory.exists"}")
  2799. )
  2800. {
  2801. command.Execute();
  2802. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2803. }
  2804. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.file.exists"}"))
  2805. {
  2806. command.Execute();
  2807. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2808. }
  2809. using (var command = client.CreateCommand($"rm -f {remoteHome + "/file.exists"}"))
  2810. {
  2811. command.Execute();
  2812. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2813. }
  2814. #endregion Clean-up
  2815. #region Setup
  2816. using (var command = client.CreateCommand($"touch {remoteHome + "/file.exists"}"))
  2817. {
  2818. command.Execute();
  2819. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2820. }
  2821. using (var command = client.CreateCommand($"mkdir {remoteHome + "/directory.exists"}"))
  2822. {
  2823. command.Execute();
  2824. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2825. }
  2826. using (var command = client.CreateCommand($"ln -s {remoteHome + "/file.exists"} {remoteHome + "/symlink.to.file.exists"}"))
  2827. {
  2828. command.Execute();
  2829. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2830. }
  2831. using (var command = client.CreateCommand($"ln -s {remoteHome + "/directory.exists"} {remoteHome + "/symlink.to.directory.exists"}"))
  2832. {
  2833. command.Execute();
  2834. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2835. }
  2836. #endregion Setup
  2837. }
  2838. #endregion Setup
  2839. #region Assert
  2840. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2841. {
  2842. client.Connect();
  2843. Assert.IsFalse(client.Exists(remoteHome + "/DoesNotExist"));
  2844. Assert.IsTrue(client.Exists(remoteHome + "/file.exists"));
  2845. Assert.IsTrue(client.Exists(remoteHome + "/symlink.to.file.exists"));
  2846. Assert.IsTrue(client.Exists(remoteHome + "/directory.exists"));
  2847. Assert.IsTrue(client.Exists(remoteHome + "/symlink.to.directory.exists"));
  2848. }
  2849. #endregion Assert
  2850. #region Teardown
  2851. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2852. {
  2853. client.Connect();
  2854. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/DoesNotExist"}"))
  2855. {
  2856. command.Execute();
  2857. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2858. }
  2859. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.directory.exists"}"))
  2860. {
  2861. command.Execute();
  2862. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2863. }
  2864. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/directory.exists"}"))
  2865. {
  2866. command.Execute();
  2867. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2868. }
  2869. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.file.exists"}"))
  2870. {
  2871. command.Execute();
  2872. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2873. }
  2874. using (var command = client.CreateCommand($"rm -f {remoteHome + "/file.exists"}"))
  2875. {
  2876. command.Execute();
  2877. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2878. }
  2879. }
  2880. #endregion Teardown
  2881. }
  2882. [TestMethod]
  2883. public async Task Sftp_ExistsAsync()
  2884. {
  2885. const string remoteHome = "/home/sshnet";
  2886. #region Setup
  2887. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2888. {
  2889. client.Connect();
  2890. #region Clean-up
  2891. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/DoesNotExist"}"))
  2892. {
  2893. await command.ExecuteAsync();
  2894. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2895. }
  2896. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.directory.exists"}"))
  2897. {
  2898. await command.ExecuteAsync();
  2899. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2900. }
  2901. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/directory.exists"}")
  2902. )
  2903. {
  2904. await command.ExecuteAsync();
  2905. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2906. }
  2907. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.file.exists"}"))
  2908. {
  2909. await command.ExecuteAsync();
  2910. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2911. }
  2912. using (var command = client.CreateCommand($"rm -f {remoteHome + "/file.exists"}"))
  2913. {
  2914. await command.ExecuteAsync();
  2915. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2916. }
  2917. #endregion Clean-up
  2918. #region Setup
  2919. using (var command = client.CreateCommand($"touch {remoteHome + "/file.exists"}"))
  2920. {
  2921. await command.ExecuteAsync();
  2922. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2923. }
  2924. using (var command = client.CreateCommand($"mkdir {remoteHome + "/directory.exists"}"))
  2925. {
  2926. await command.ExecuteAsync();
  2927. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2928. }
  2929. using (var command = client.CreateCommand($"ln -s {remoteHome + "/file.exists"} {remoteHome + "/symlink.to.file.exists"}"))
  2930. {
  2931. await command.ExecuteAsync();
  2932. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2933. }
  2934. using (var command = client.CreateCommand($"ln -s {remoteHome + "/directory.exists"} {remoteHome + "/symlink.to.directory.exists"}"))
  2935. {
  2936. await command.ExecuteAsync();
  2937. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2938. }
  2939. #endregion Setup
  2940. }
  2941. #endregion Setup
  2942. #region Assert
  2943. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  2944. {
  2945. await client.ConnectAsync(default).ConfigureAwait(false);
  2946. Assert.IsFalse(await client.ExistsAsync(remoteHome + "/DoesNotExist"));
  2947. Assert.IsTrue(await client.ExistsAsync(remoteHome + "/file.exists"));
  2948. Assert.IsTrue(await client.ExistsAsync(remoteHome + "/symlink.to.file.exists"));
  2949. Assert.IsTrue(await client.ExistsAsync(remoteHome + "/directory.exists"));
  2950. Assert.IsTrue(await client.ExistsAsync(remoteHome + "/symlink.to.directory.exists"));
  2951. }
  2952. #endregion Assert
  2953. #region Teardown
  2954. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2955. {
  2956. client.Connect();
  2957. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/DoesNotExist"}"))
  2958. {
  2959. await command.ExecuteAsync();
  2960. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2961. }
  2962. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.directory.exists"}"))
  2963. {
  2964. await command.ExecuteAsync();
  2965. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2966. }
  2967. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/directory.exists"}"))
  2968. {
  2969. await command.ExecuteAsync();
  2970. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2971. }
  2972. using (var command = client.CreateCommand($"rm -Rf {remoteHome + "/symlink.to.file.exists"}"))
  2973. {
  2974. await command.ExecuteAsync();
  2975. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2976. }
  2977. using (var command = client.CreateCommand($"rm -f {remoteHome + "/file.exists"}"))
  2978. {
  2979. await command.ExecuteAsync();
  2980. Assert.AreEqual(0, command.ExitStatus, command.Error);
  2981. }
  2982. }
  2983. #endregion Teardown
  2984. }
  2985. [TestMethod]
  2986. public void Sftp_ListDirectory()
  2987. {
  2988. const string remoteDirectory = "/home/sshnet/test123";
  2989. try
  2990. {
  2991. using (var client = new SshClient(_connectionInfoFactory.Create()))
  2992. {
  2993. client.Connect();
  2994. client.RunCommand($@"rm -Rf ""{remoteDirectory}""");
  2995. client.RunCommand($@"mkdir -p ""{remoteDirectory}""");
  2996. client.RunCommand($@"mkdir -p ""{remoteDirectory}/sub""");
  2997. client.RunCommand($@"touch ""{remoteDirectory}/file1""");
  2998. client.RunCommand($@"touch ""{remoteDirectory}/file2""");
  2999. }
  3000. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3001. {
  3002. client.Connect();
  3003. client.ChangeDirectory(remoteDirectory);
  3004. var directoryContent = client.ListDirectory(".").OrderBy(p => p.Name).ToList();
  3005. Assert.AreEqual(5, directoryContent.Count);
  3006. Assert.AreEqual(".", directoryContent[0].Name);
  3007. Assert.AreEqual($"{remoteDirectory}/.", directoryContent[0].FullName);
  3008. Assert.IsTrue(directoryContent[0].IsDirectory);
  3009. Assert.AreEqual("..", directoryContent[1].Name);
  3010. Assert.AreEqual($"{remoteDirectory}/..", directoryContent[1].FullName);
  3011. Assert.IsTrue(directoryContent[1].IsDirectory);
  3012. Assert.AreEqual("file1", directoryContent[2].Name);
  3013. Assert.AreEqual($"{remoteDirectory}/file1", directoryContent[2].FullName);
  3014. Assert.IsFalse(directoryContent[2].IsDirectory);
  3015. Assert.AreEqual("file2", directoryContent[3].Name);
  3016. Assert.AreEqual($"{remoteDirectory}/file2", directoryContent[3].FullName);
  3017. Assert.IsFalse(directoryContent[3].IsDirectory);
  3018. Assert.AreEqual("sub", directoryContent[4].Name);
  3019. Assert.AreEqual($"{remoteDirectory}/sub", directoryContent[4].FullName);
  3020. Assert.IsTrue(directoryContent[4].IsDirectory);
  3021. }
  3022. }
  3023. finally
  3024. {
  3025. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3026. {
  3027. client.Connect();
  3028. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3029. {
  3030. command.Execute();
  3031. }
  3032. }
  3033. }
  3034. }
  3035. [TestMethod]
  3036. public void Sftp_ChangeDirectory_DirectoryDoesNotExist()
  3037. {
  3038. const string remoteDirectory = "/home/sshnet/test123";
  3039. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3040. {
  3041. client.Connect();
  3042. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3043. {
  3044. command.Execute();
  3045. }
  3046. }
  3047. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3048. {
  3049. client.Connect();
  3050. try
  3051. {
  3052. client.ChangeDirectory(remoteDirectory);
  3053. Assert.Fail();
  3054. }
  3055. catch (SftpPathNotFoundException)
  3056. {
  3057. }
  3058. }
  3059. }
  3060. [TestMethod]
  3061. public async Task Sftp_ChangeDirectory_DirectoryDoesNotExistAsync()
  3062. {
  3063. const string remoteDirectory = "/home/sshnet/test123";
  3064. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3065. {
  3066. await client.ConnectAsync(CancellationToken.None).ConfigureAwait(false);
  3067. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3068. {
  3069. await command.ExecuteAsync(CancellationToken.None).ConfigureAwait(false);
  3070. }
  3071. }
  3072. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3073. {
  3074. client.Connect();
  3075. try
  3076. {
  3077. await client.ChangeDirectoryAsync(remoteDirectory, CancellationToken.None).ConfigureAwait(false);
  3078. Assert.Fail();
  3079. }
  3080. catch (SftpPathNotFoundException)
  3081. {
  3082. }
  3083. }
  3084. }
  3085. [TestMethod]
  3086. public void Sftp_ChangeDirectory_DirectoryExists()
  3087. {
  3088. const string remoteDirectory = "/home/sshnet/test123";
  3089. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3090. {
  3091. client.Connect();
  3092. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3093. {
  3094. command.Execute();
  3095. }
  3096. using (var command = client.CreateCommand("mkdir -p " + _remotePathTransformation.Transform(remoteDirectory)))
  3097. {
  3098. command.Execute();
  3099. }
  3100. }
  3101. try
  3102. {
  3103. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3104. {
  3105. client.Connect();
  3106. client.ChangeDirectory(remoteDirectory);
  3107. Assert.AreEqual(remoteDirectory, client.WorkingDirectory);
  3108. using (var uploadStream = CreateMemoryStream(100))
  3109. {
  3110. uploadStream.Position = 0;
  3111. client.UploadFile(uploadStream, "gert.txt");
  3112. uploadStream.Position = 0;
  3113. using (var downloadStream = client.OpenRead(remoteDirectory + "/gert.txt"))
  3114. {
  3115. Assert.AreEqual(CreateHash(uploadStream), CreateHash(downloadStream));
  3116. }
  3117. }
  3118. }
  3119. }
  3120. finally
  3121. {
  3122. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3123. {
  3124. client.Connect();
  3125. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3126. {
  3127. command.Execute();
  3128. }
  3129. }
  3130. }
  3131. }
  3132. [TestMethod]
  3133. public async Task Sftp_ChangeDirectory_DirectoryExistsAsync()
  3134. {
  3135. const string remoteDirectory = "/home/sshnet/test123";
  3136. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3137. {
  3138. await client.ConnectAsync(CancellationToken.None).ConfigureAwait(false);
  3139. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3140. {
  3141. await command.ExecuteAsync(CancellationToken.None).ConfigureAwait(false);
  3142. }
  3143. using (var command = client.CreateCommand("mkdir -p " + _remotePathTransformation.Transform(remoteDirectory)))
  3144. {
  3145. await command.ExecuteAsync(CancellationToken.None).ConfigureAwait(false);
  3146. }
  3147. }
  3148. try
  3149. {
  3150. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3151. {
  3152. await client.ConnectAsync(CancellationToken.None).ConfigureAwait(false);
  3153. await client.ChangeDirectoryAsync(remoteDirectory, CancellationToken.None).ConfigureAwait(false);
  3154. Assert.AreEqual(remoteDirectory, client.WorkingDirectory);
  3155. using (var uploadStream = CreateMemoryStream(100))
  3156. {
  3157. uploadStream.Position = 0;
  3158. await client.UploadFileAsync(uploadStream, "gert.txt").ConfigureAwait(false);
  3159. uploadStream.Position = 0;
  3160. using (var downloadStream = client.OpenRead(remoteDirectory + "/gert.txt"))
  3161. {
  3162. Assert.AreEqual(CreateHash(uploadStream), CreateHash(downloadStream));
  3163. }
  3164. }
  3165. }
  3166. }
  3167. finally
  3168. {
  3169. using (var client = new SshClient(_connectionInfoFactory.Create()))
  3170. {
  3171. await client.ConnectAsync(CancellationToken.None).ConfigureAwait(false);
  3172. using (var command = client.CreateCommand("rm -Rf " + _remotePathTransformation.Transform(remoteDirectory)))
  3173. {
  3174. await command.ExecuteAsync(CancellationToken.None).ConfigureAwait(false);
  3175. }
  3176. }
  3177. }
  3178. }
  3179. [TestMethod]
  3180. public void Sftp_SubsystemExecution_Failed()
  3181. {
  3182. var remoteSshdConfig = new RemoteSshd(_adminConnectionInfoFactory).OpenConfig();
  3183. // Disable SFTP subsystem
  3184. remoteSshdConfig.ClearSubsystems()
  3185. .Update()
  3186. .Restart();
  3187. var remoteSshdReconfiguredToDefaultState = false;
  3188. try
  3189. {
  3190. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3191. {
  3192. try
  3193. {
  3194. client.Connect();
  3195. Assert.Fail("Establishing SFTP connection should have failed.");
  3196. }
  3197. catch (SshException ex)
  3198. {
  3199. Assert.IsNull(ex.InnerException);
  3200. Assert.AreEqual("Subsystem 'sftp' could not be executed.", ex.Message);
  3201. }
  3202. // Re-enable SFTP subsystem
  3203. remoteSshdConfig.Reset();
  3204. remoteSshdReconfiguredToDefaultState = true;
  3205. // ensure we can reconnect the same SftpClient instance
  3206. client.Connect();
  3207. // ensure SFTP session is correctly established
  3208. Assert.IsTrue(client.Exists("."));
  3209. }
  3210. }
  3211. finally
  3212. {
  3213. if (!remoteSshdReconfiguredToDefaultState)
  3214. {
  3215. remoteSshdConfig.Reset();
  3216. }
  3217. }
  3218. }
  3219. [TestMethod]
  3220. public void Sftp_SftpFileStream_ReadAndWrite()
  3221. {
  3222. TestReadAndWrite(
  3223. (s, buffer, offset, count) => s.Read(buffer, offset, count),
  3224. (s, buffer, offset, count) => s.Write(buffer, offset, count));
  3225. }
  3226. [TestMethod]
  3227. public void Sftp_SftpFileStream_ReadAndWriteByte()
  3228. {
  3229. TestReadAndWrite(
  3230. read: (s, buffer, offset, count) =>
  3231. {
  3232. int bytesRead = 0;
  3233. int b;
  3234. while (bytesRead < count && (b = s.ReadByte()) != -1)
  3235. {
  3236. buffer[offset + bytesRead] = (byte)b;
  3237. bytesRead++;
  3238. }
  3239. return bytesRead;
  3240. },
  3241. write: (s, buffer, offset, count) =>
  3242. {
  3243. for (int i = 0; i < count; i++)
  3244. {
  3245. s.WriteByte(buffer[offset + i]);
  3246. }
  3247. });
  3248. }
  3249. [TestMethod]
  3250. public void Sftp_SftpFileStream_ReadAndWriteAsync()
  3251. {
  3252. TestReadAndWrite(
  3253. (s, buffer, offset, count) => s.ReadAsync(buffer, offset, count).GetAwaiter().GetResult(),
  3254. (s, buffer, offset, count) => s.WriteAsync(buffer, offset, count).GetAwaiter().GetResult());
  3255. }
  3256. [TestMethod]
  3257. public void Sftp_SftpFileStream_ReadAndWriteBeginEnd()
  3258. {
  3259. TestReadAndWrite(
  3260. (s, buffer, offset, count) => s.EndRead(s.BeginRead(buffer, offset, count, null, null)),
  3261. (s, buffer, offset, count) => s.EndWrite(s.BeginWrite(buffer, offset, count, null, null)));
  3262. }
  3263. #if NET
  3264. [TestMethod]
  3265. public void Sftp_SftpFileStream_ReadAndWriteSpan()
  3266. {
  3267. TestReadAndWrite(
  3268. (s, buffer, offset, count) => s.Read(buffer.AsSpan(offset, count)),
  3269. (s, buffer, offset, count) => s.Write(buffer.AsSpan(offset, count)));
  3270. }
  3271. [TestMethod]
  3272. public void Sftp_SftpFileStream_ReadAndWriteAsyncMemory()
  3273. {
  3274. TestReadAndWrite(
  3275. (s, buffer, offset, count) => s.ReadAsync(buffer.AsMemory(offset, count)).AsTask().GetAwaiter().GetResult(),
  3276. (s, buffer, offset, count) => s.WriteAsync(buffer.AsMemory(offset, count)).AsTask().GetAwaiter().GetResult());
  3277. }
  3278. #endif
  3279. private void TestReadAndWrite(
  3280. Func<SftpFileStream, byte[], int, int, int> read,
  3281. Action<SftpFileStream, byte[], int, int> write)
  3282. {
  3283. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3284. {
  3285. client.Connect();
  3286. var remoteFile = GenerateUniqueRemoteFileName();
  3287. if (client.Exists(remoteFile))
  3288. {
  3289. client.DeleteFile(remoteFile);
  3290. }
  3291. try
  3292. {
  3293. using (var s = client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write))
  3294. {
  3295. Assert.IsFalse(s.CanRead);
  3296. Assert.IsTrue(s.CanWrite);
  3297. write(s, new byte[] { 5, 4, 3, 2, 1 }, 1, 3);
  3298. }
  3299. // switch from read to write mode
  3300. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3301. {
  3302. Assert.IsTrue(s.CanRead);
  3303. Assert.IsTrue(s.CanWrite);
  3304. Assert.AreEqual(4, ReadByte(s));
  3305. Assert.AreEqual(3, ReadByte(s));
  3306. Assert.AreEqual(2, s.Position);
  3307. WriteByte(s, 7);
  3308. write(s, new byte[] { 8, 9, 10, 11, 12 }, 1, 3);
  3309. Assert.AreEqual(6, s.Position);
  3310. }
  3311. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3312. {
  3313. Assert.IsTrue(s.CanRead);
  3314. Assert.IsFalse(s.CanWrite);
  3315. Assert.AreEqual(6, s.Length);
  3316. var buffer = new byte[s.Length];
  3317. Assert.AreEqual(6, read(s, buffer, 0, buffer.Length));
  3318. CollectionAssert.AreEqual(new byte[] { 4, 3, 7, 9, 10, 11 }, buffer);
  3319. // Ensure we've reached end of the stream
  3320. Assert.AreEqual(-1, ReadByte(s));
  3321. }
  3322. // switch from read to write mode, and back to read mode and finally
  3323. // append a byte
  3324. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3325. {
  3326. Assert.AreEqual(4, ReadByte(s));
  3327. Assert.AreEqual(3, ReadByte(s));
  3328. Assert.AreEqual(7, ReadByte(s));
  3329. write(s, new byte[] { 0, 1, 6, 4 }, 1, 2);
  3330. Assert.AreEqual(11, ReadByte(s));
  3331. // Ensure we've reached end of the stream
  3332. Assert.AreEqual(-1, ReadByte(s));
  3333. WriteByte(s, 12);
  3334. }
  3335. // switch from write to read mode, and back to write mode
  3336. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3337. {
  3338. WriteByte(s, 5);
  3339. Assert.AreEqual(3, ReadByte(s));
  3340. WriteByte(s, 13);
  3341. Assert.AreEqual(3, s.Position);
  3342. }
  3343. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3344. {
  3345. Assert.AreEqual(7, s.Length);
  3346. var buffer = new byte[s.Length];
  3347. Assert.AreEqual(7, read(s, buffer, 0, buffer.Length));
  3348. CollectionAssert.AreEqual(new byte[] { 5, 3, 13, 1, 6, 11, 12 }, buffer);
  3349. // Ensure we've reached end of the stream
  3350. Assert.AreEqual(-1, ReadByte(s));
  3351. }
  3352. }
  3353. finally
  3354. {
  3355. if (client.Exists(remoteFile))
  3356. {
  3357. client.DeleteFile(remoteFile);
  3358. }
  3359. }
  3360. }
  3361. int ReadByte(SftpFileStream s)
  3362. {
  3363. var buffer = new byte[1];
  3364. var bytesRead = read(s, buffer, 0, 1);
  3365. return bytesRead == 0 ? -1 : buffer[0];
  3366. }
  3367. void WriteByte(SftpFileStream s, byte b)
  3368. {
  3369. write(s, [b], 0, 1);
  3370. }
  3371. }
  3372. [TestMethod]
  3373. public void Sftp_SftpFileStream_SetLength_ReduceLength()
  3374. {
  3375. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3376. {
  3377. client.Connect();
  3378. var remoteFile = GenerateUniqueRemoteFileName();
  3379. if (client.Exists(remoteFile))
  3380. {
  3381. client.DeleteFile(remoteFile);
  3382. }
  3383. try
  3384. {
  3385. using (var s = client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write))
  3386. {
  3387. s.Write(new byte[] { 5, 4, 3, 2, 1 }, 1, 3);
  3388. }
  3389. // reduce length while in write mode, with data in write buffer, and before
  3390. // current position
  3391. using (var s = client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  3392. {
  3393. s.Position = 3;
  3394. s.Write(new byte[] { 6, 7, 8, 9 }, offset: 0, count: 4);
  3395. Assert.AreEqual(7, s.Position);
  3396. // verify buffer has not yet been flushed
  3397. using (var fs = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3398. {
  3399. Assert.AreEqual(4, fs.ReadByte());
  3400. Assert.AreEqual(3, fs.ReadByte());
  3401. Assert.AreEqual(2, fs.ReadByte());
  3402. // Ensure we've reached end of the stream
  3403. Assert.AreEqual(-1, fs.ReadByte());
  3404. }
  3405. s.SetLength(5);
  3406. Assert.AreEqual(5, s.Position);
  3407. // verify that buffer was flushed and size has been modified
  3408. using (var fs = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3409. {
  3410. Assert.AreEqual(4, fs.ReadByte());
  3411. Assert.AreEqual(3, fs.ReadByte());
  3412. Assert.AreEqual(2, fs.ReadByte());
  3413. Assert.AreEqual(6, fs.ReadByte());
  3414. Assert.AreEqual(7, fs.ReadByte());
  3415. // Ensure we've reached end of the stream
  3416. Assert.AreEqual(-1, fs.ReadByte());
  3417. }
  3418. s.WriteByte(1);
  3419. }
  3420. // verify that last byte was correctly written to the file
  3421. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3422. {
  3423. Assert.AreEqual(6, s.Length);
  3424. var buffer = new byte[s.Length + 2];
  3425. Assert.AreEqual(6, s.Read(buffer, offset: 0, buffer.Length));
  3426. CollectionAssert.AreEqual(new byte[] { 4, 3, 2, 6, 7, 1, 0, 0 }, buffer);
  3427. // Ensure we've reached end of the stream
  3428. Assert.AreEqual(-1, s.ReadByte());
  3429. }
  3430. // reduce length while in read mode, but beyond current position
  3431. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3432. {
  3433. var buffer = new byte[1];
  3434. Assert.AreEqual(1, s.Read(buffer, offset: 0, buffer.Length));
  3435. CollectionAssert.AreEqual(new byte[] { 4 }, buffer);
  3436. s.SetLength(3);
  3437. using (var w = client.Open(remoteFile, FileMode.Open, FileAccess.Write))
  3438. {
  3439. w.Write(new byte[] { 8, 1, 6, 2 }, offset: 0, count: 4);
  3440. }
  3441. // verify that position was not changed
  3442. Assert.AreEqual(1, s.Position);
  3443. // verify that read buffer was cleared
  3444. Assert.AreEqual(1, s.ReadByte());
  3445. Assert.AreEqual(6, s.ReadByte());
  3446. Assert.AreEqual(2, s.ReadByte());
  3447. // Ensure we've reached end of the stream
  3448. Assert.AreEqual(-1, s.ReadByte());
  3449. Assert.AreEqual(4, s.Length);
  3450. }
  3451. // reduce length while in read mode, but before current position
  3452. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.ReadWrite))
  3453. {
  3454. var buffer = new byte[4];
  3455. Assert.AreEqual(4, s.Read(buffer, offset: 0, buffer.Length));
  3456. CollectionAssert.AreEqual(new byte[] { 8, 1, 6, 2 }, buffer);
  3457. Assert.AreEqual(4, s.Position);
  3458. s.SetLength(3);
  3459. // verify that position was moved to last byte
  3460. Assert.AreEqual(3, s.Position);
  3461. using (var w = client.Open(remoteFile, FileMode.Open, FileAccess.Read))
  3462. {
  3463. Assert.AreEqual(3, w.Length);
  3464. Assert.AreEqual(8, w.ReadByte());
  3465. Assert.AreEqual(1, w.ReadByte());
  3466. Assert.AreEqual(6, w.ReadByte());
  3467. // Ensure we've reached end of the stream
  3468. Assert.AreEqual(-1, w.ReadByte());
  3469. }
  3470. // Ensure we've reached end of the stream
  3471. Assert.AreEqual(-1, s.ReadByte());
  3472. }
  3473. }
  3474. finally
  3475. {
  3476. if (client.Exists(remoteFile))
  3477. {
  3478. client.DeleteFile(remoteFile);
  3479. }
  3480. }
  3481. }
  3482. }
  3483. [TestMethod]
  3484. public void Sftp_SftpFileStream_Seek_BeyondEndOfFile_SeekOriginBegin()
  3485. {
  3486. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3487. {
  3488. client.BufferSize = 500;
  3489. client.Connect();
  3490. var remoteFile = GenerateUniqueRemoteFileName();
  3491. if (client.Exists(remoteFile))
  3492. {
  3493. client.DeleteFile(remoteFile);
  3494. }
  3495. try
  3496. {
  3497. // create single-byte file
  3498. using (var fs = client.OpenWrite(remoteFile))
  3499. {
  3500. fs.WriteByte(0x04);
  3501. }
  3502. // seek beyond EOF but not beyond buffer size
  3503. // do not write anything
  3504. using (var fs = client.OpenWrite(remoteFile))
  3505. {
  3506. var newPosition = fs.Seek(offset: 3L, SeekOrigin.Begin);
  3507. Assert.AreEqual(3, newPosition);
  3508. Assert.AreEqual(3, fs.Position);
  3509. Assert.AreEqual(1, fs.Length);
  3510. }
  3511. using (var fs = client.OpenRead(remoteFile))
  3512. {
  3513. Assert.AreEqual(1, fs.Length);
  3514. Assert.AreEqual(0x04, fs.ReadByte());
  3515. // Ensure we've reached end of the stream
  3516. Assert.AreEqual(-1, fs.ReadByte());
  3517. }
  3518. client.DeleteFile(remoteFile);
  3519. // create single-byte file
  3520. using (var fs = client.OpenWrite(remoteFile))
  3521. {
  3522. fs.WriteByte(0x04);
  3523. }
  3524. // seek beyond EOF and beyond buffer size
  3525. // do not write anything
  3526. using (var fs = client.OpenWrite(remoteFile))
  3527. {
  3528. var newPosition = fs.Seek(offset: 700L, SeekOrigin.Begin);
  3529. Assert.AreEqual(700, newPosition);
  3530. Assert.AreEqual(700, fs.Position);
  3531. Assert.AreEqual(1, fs.Length);
  3532. }
  3533. using (var fs = client.OpenRead(remoteFile))
  3534. {
  3535. Assert.AreEqual(1, fs.Length);
  3536. Assert.AreEqual(0x04, fs.ReadByte());
  3537. // Ensure we've reached end of the stream
  3538. Assert.AreEqual(-1, fs.ReadByte());
  3539. }
  3540. client.DeleteFile(remoteFile);
  3541. // create single-byte file
  3542. using (var fs = client.OpenWrite(remoteFile))
  3543. {
  3544. fs.WriteByte(0x04);
  3545. }
  3546. // seek beyond EOF but not beyond buffer size
  3547. // write less bytes than buffer size
  3548. var seekOffset = 3L;
  3549. // buffer holding the data that we'll write to the file
  3550. var writeBuffer = GenerateRandom(size: 7);
  3551. using (var fs = client.OpenWrite(remoteFile))
  3552. {
  3553. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  3554. Assert.AreEqual(seekOffset, newPosition);
  3555. Assert.AreEqual(seekOffset, fs.Position);
  3556. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3557. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  3558. }
  3559. using (var fs = client.OpenRead(remoteFile))
  3560. {
  3561. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  3562. Assert.AreEqual(0x04, fs.ReadByte());
  3563. var soughtOverReadBuffer = new byte[seekOffset - 1];
  3564. fs.ReadExactly(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length);
  3565. CollectionAssert.AreEqual(new byte[soughtOverReadBuffer.Length], soughtOverReadBuffer);
  3566. var readBuffer = new byte[writeBuffer.Length];
  3567. fs.ReadExactly(readBuffer, offset: 0, readBuffer.Length);
  3568. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  3569. // Ensure we've reached end of the stream
  3570. Assert.AreEqual(-1, fs.ReadByte());
  3571. }
  3572. client.DeleteFile(remoteFile);
  3573. // create single-byte file
  3574. using (var fs = client.OpenWrite(remoteFile))
  3575. {
  3576. fs.WriteByte(0x04);
  3577. }
  3578. // seek beyond EOF and beyond buffer size
  3579. // write less bytes than buffer size
  3580. seekOffset = 700L;
  3581. // buffer holding the data that we'll write to the file
  3582. writeBuffer = GenerateRandom(size: 4);
  3583. using (var fs = client.OpenWrite(remoteFile))
  3584. {
  3585. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  3586. Assert.AreEqual(seekOffset, newPosition);
  3587. Assert.AreEqual(seekOffset, fs.Position);
  3588. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3589. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  3590. }
  3591. using (var fs = client.OpenRead(remoteFile))
  3592. {
  3593. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  3594. Assert.AreEqual(0x04, fs.ReadByte());
  3595. var soughtOverReadBuffer = new byte[seekOffset - 1];
  3596. fs.ReadExactly(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length);
  3597. CollectionAssert.AreEqual(new byte[soughtOverReadBuffer.Length], soughtOverReadBuffer);
  3598. var readBuffer = new byte[writeBuffer.Length];
  3599. fs.ReadExactly(readBuffer, offset: 0, readBuffer.Length);
  3600. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  3601. // Ensure we've reached end of the stream
  3602. Assert.AreEqual(-1, fs.ReadByte());
  3603. }
  3604. client.DeleteFile(remoteFile);
  3605. // create single-byte file
  3606. using (var fs = client.OpenWrite(remoteFile))
  3607. {
  3608. fs.WriteByte(0x04);
  3609. }
  3610. // seek beyond EOF but not beyond buffer size
  3611. // write more bytes than buffer size
  3612. writeBuffer = GenerateRandom(size: 600);
  3613. using (var fs = client.OpenWrite(remoteFile))
  3614. {
  3615. var newPosition = fs.Seek(offset: 3L, SeekOrigin.Begin);
  3616. Assert.AreEqual(3, newPosition);
  3617. Assert.AreEqual(3, fs.Position);
  3618. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3619. }
  3620. using (var fs = client.OpenRead(remoteFile))
  3621. {
  3622. Assert.AreEqual(3 + writeBuffer.Length, fs.Length);
  3623. Assert.AreEqual(0x04, fs.ReadByte());
  3624. Assert.AreEqual(0x00, fs.ReadByte());
  3625. Assert.AreEqual(0x00, fs.ReadByte());
  3626. var readBuffer = new byte[writeBuffer.Length];
  3627. fs.ReadExactly(readBuffer, offset: 0, readBuffer.Length);
  3628. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  3629. // Ensure we've reached end of the stream
  3630. Assert.AreEqual(-1, fs.ReadByte());
  3631. }
  3632. client.DeleteFile(remoteFile);
  3633. // create single-byte file
  3634. using (var fs = client.OpenWrite(remoteFile))
  3635. {
  3636. fs.WriteByte(0x04);
  3637. }
  3638. // seek beyond EOF and beyond buffer size
  3639. // write more bytes than buffer size
  3640. writeBuffer = GenerateRandom(size: 600);
  3641. using (var fs = client.OpenWrite(remoteFile))
  3642. {
  3643. var newPosition = fs.Seek(offset: 550, SeekOrigin.Begin);
  3644. Assert.AreEqual(550, newPosition);
  3645. Assert.AreEqual(550, fs.Position);
  3646. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3647. }
  3648. using (var fs = client.OpenRead(remoteFile))
  3649. {
  3650. Assert.AreEqual(550 + writeBuffer.Length, fs.Length);
  3651. Assert.AreEqual(0x04, fs.ReadByte());
  3652. var soughtOverReadBuffer = new byte[550 - 1];
  3653. fs.ReadExactly(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length);
  3654. CollectionAssert.AreEqual(new byte[550 - 1], soughtOverReadBuffer);
  3655. var readBuffer = new byte[writeBuffer.Length];
  3656. fs.ReadExactly(readBuffer, offset: 0, readBuffer.Length);
  3657. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  3658. // Ensure we've reached end of the stream
  3659. Assert.AreEqual(-1, fs.ReadByte());
  3660. }
  3661. }
  3662. finally
  3663. {
  3664. if (client.Exists(remoteFile))
  3665. {
  3666. client.DeleteFile(remoteFile);
  3667. }
  3668. }
  3669. }
  3670. }
  3671. [TestMethod]
  3672. public void Sftp_SftpFileStream_Seek_BeyondEndOfFile_SeekOriginEnd()
  3673. {
  3674. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3675. {
  3676. client.BufferSize = 500;
  3677. client.Connect();
  3678. var remoteFile = GenerateUniqueRemoteFileName();
  3679. if (client.Exists(remoteFile))
  3680. {
  3681. client.DeleteFile(remoteFile);
  3682. }
  3683. try
  3684. {
  3685. // create single-byte file
  3686. using (var fs = client.OpenWrite(remoteFile))
  3687. {
  3688. fs.WriteByte(0x04);
  3689. }
  3690. // seek beyond EOF but not beyond buffer size
  3691. // do not write anything
  3692. using (var fs = client.OpenWrite(remoteFile))
  3693. {
  3694. var newPosition = fs.Seek(offset: 3L, SeekOrigin.End);
  3695. Assert.AreEqual(4, newPosition);
  3696. Assert.AreEqual(4, fs.Position);
  3697. Assert.AreEqual(1, fs.Length);
  3698. }
  3699. using (var fs = client.OpenRead(remoteFile))
  3700. {
  3701. Assert.AreEqual(1, fs.Length);
  3702. Assert.AreEqual(0x04, fs.ReadByte());
  3703. // Ensure we've reached end of the stream
  3704. Assert.AreEqual(-1, fs.ReadByte());
  3705. }
  3706. client.DeleteFile(remoteFile);
  3707. // create single-byte file
  3708. using (var fs = client.OpenWrite(remoteFile))
  3709. {
  3710. fs.WriteByte(0x04);
  3711. }
  3712. // seek beyond EOF and beyond buffer size
  3713. // do not write anything
  3714. using (var fs = client.OpenWrite(remoteFile))
  3715. {
  3716. var newPosition = fs.Seek(offset: 700L, SeekOrigin.End);
  3717. Assert.AreEqual(701, newPosition);
  3718. Assert.AreEqual(701, fs.Position);
  3719. Assert.AreEqual(1, fs.Length);
  3720. }
  3721. using (var fs = client.OpenRead(remoteFile))
  3722. {
  3723. Assert.AreEqual(1, fs.Length);
  3724. Assert.AreEqual(0x04, fs.ReadByte());
  3725. // Ensure we've reached end of the stream
  3726. Assert.AreEqual(-1, fs.ReadByte());
  3727. }
  3728. client.DeleteFile(remoteFile);
  3729. // create single-byte file
  3730. using (var fs = client.OpenWrite(remoteFile))
  3731. {
  3732. fs.WriteByte(0x04);
  3733. }
  3734. // seek beyond EOF but not beyond buffer size
  3735. // write less bytes than buffer size
  3736. var seekOffset = 3L;
  3737. // buffer holding the data that we'll write to the file
  3738. var writeBuffer = GenerateRandom(size: 7);
  3739. using (var fs = client.OpenWrite(remoteFile))
  3740. {
  3741. var newPosition = fs.Seek(seekOffset, SeekOrigin.End);
  3742. Assert.AreEqual(4, newPosition);
  3743. Assert.AreEqual(4, fs.Position);
  3744. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3745. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  3746. }
  3747. using (var fs = client.OpenRead(remoteFile))
  3748. {
  3749. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  3750. Assert.AreEqual(0x04, fs.ReadByte());
  3751. var soughtOverReadBuffer = new byte[seekOffset];
  3752. fs.ReadExactly(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length);
  3753. CollectionAssert.AreEqual(new byte[soughtOverReadBuffer.Length], soughtOverReadBuffer);
  3754. var readBuffer = new byte[writeBuffer.Length];
  3755. fs.ReadExactly(readBuffer, offset: 0, readBuffer.Length);
  3756. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  3757. // Ensure we've reached end of the stream
  3758. Assert.AreEqual(-1, fs.ReadByte());
  3759. }
  3760. client.DeleteFile(remoteFile);
  3761. // create single-byte file
  3762. using (var fs = client.OpenWrite(remoteFile))
  3763. {
  3764. fs.WriteByte(0x04);
  3765. }
  3766. // seek beyond EOF and beyond buffer size
  3767. // write less bytes than buffer size
  3768. seekOffset = 700L;
  3769. // buffer holding the data that we'll write to the file
  3770. writeBuffer = GenerateRandom(size: 4);
  3771. using (var fs = client.OpenWrite(remoteFile))
  3772. {
  3773. var newPosition = fs.Seek(seekOffset, SeekOrigin.End);
  3774. Assert.AreEqual(1 + seekOffset, newPosition);
  3775. Assert.AreEqual(1 + seekOffset, fs.Position);
  3776. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3777. }
  3778. using (var fs = client.OpenRead(remoteFile))
  3779. {
  3780. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  3781. Assert.AreEqual(0x04, fs.ReadByte());
  3782. var soughtOverReadBuffer = new byte[seekOffset];
  3783. fs.ReadExactly(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length);
  3784. CollectionAssert.AreEqual(new byte[soughtOverReadBuffer.Length], soughtOverReadBuffer);
  3785. var readBuffer = new byte[writeBuffer.Length];
  3786. fs.ReadExactly(readBuffer, offset: 0, readBuffer.Length);
  3787. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  3788. // Ensure we've reached end of the stream
  3789. Assert.AreEqual(-1, fs.ReadByte());
  3790. }
  3791. client.DeleteFile(remoteFile);
  3792. // create single-byte file
  3793. using (var fs = client.OpenWrite(remoteFile))
  3794. {
  3795. fs.WriteByte(0x04);
  3796. }
  3797. // seek beyond EOF but not beyond buffer size
  3798. // write more bytes than buffer size
  3799. seekOffset = 3L;
  3800. writeBuffer = GenerateRandom(size: 600);
  3801. using (var fs = client.OpenWrite(remoteFile))
  3802. {
  3803. var newPosition = fs.Seek(seekOffset, SeekOrigin.End);
  3804. Assert.AreEqual(1 + seekOffset, newPosition);
  3805. Assert.AreEqual(1 + seekOffset, fs.Position);
  3806. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3807. }
  3808. using (var fs = client.OpenRead(remoteFile))
  3809. {
  3810. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  3811. Assert.AreEqual(0x04, fs.ReadByte());
  3812. var soughtOverReadBuffer = new byte[seekOffset];
  3813. fs.ReadExactly(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length);
  3814. CollectionAssert.AreEqual(new byte[soughtOverReadBuffer.Length], soughtOverReadBuffer);
  3815. var readBuffer = new byte[writeBuffer.Length];
  3816. fs.ReadExactly(readBuffer, offset: 0, readBuffer.Length);
  3817. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  3818. // Ensure we've reached end of the stream
  3819. Assert.AreEqual(-1, fs.ReadByte());
  3820. }
  3821. client.DeleteFile(remoteFile);
  3822. // create single-byte file
  3823. using (var fs = client.OpenWrite(remoteFile))
  3824. {
  3825. fs.WriteByte(0x04);
  3826. }
  3827. // seek beyond EOF and beyond buffer size
  3828. // write more bytes than buffer size
  3829. seekOffset = 550L;
  3830. writeBuffer = GenerateRandom(size: 600);
  3831. using (var fs = client.OpenWrite(remoteFile))
  3832. {
  3833. var newPosition = fs.Seek(seekOffset, SeekOrigin.End);
  3834. Assert.AreEqual(1 + seekOffset, newPosition);
  3835. Assert.AreEqual(1 + seekOffset, fs.Position);
  3836. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3837. }
  3838. using (var fs = client.OpenRead(remoteFile))
  3839. {
  3840. Assert.AreEqual(1 + seekOffset + writeBuffer.Length, fs.Length);
  3841. Assert.AreEqual(0x04, fs.ReadByte());
  3842. var soughtOverReadBuffer = new byte[seekOffset];
  3843. fs.ReadExactly(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length);
  3844. CollectionAssert.AreEqual(new byte[soughtOverReadBuffer.Length], soughtOverReadBuffer);
  3845. var readBuffer = new byte[writeBuffer.Length];
  3846. fs.ReadExactly(readBuffer, offset: 0, readBuffer.Length);
  3847. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  3848. // Ensure we've reached end of the stream
  3849. Assert.AreEqual(-1, fs.ReadByte());
  3850. }
  3851. }
  3852. finally
  3853. {
  3854. if (client.Exists(remoteFile))
  3855. {
  3856. client.DeleteFile(remoteFile);
  3857. }
  3858. }
  3859. }
  3860. }
  3861. [TestMethod]
  3862. public void Sftp_SftpFileStream_Seek_NegativeOffSet_SeekOriginEnd()
  3863. {
  3864. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  3865. {
  3866. client.BufferSize = 500;
  3867. client.Connect();
  3868. var remoteFile = GenerateUniqueRemoteFileName();
  3869. if (client.Exists(remoteFile))
  3870. {
  3871. client.DeleteFile(remoteFile);
  3872. }
  3873. try
  3874. {
  3875. using (var fs = client.OpenWrite(remoteFile))
  3876. {
  3877. fs.WriteByte(0x04);
  3878. fs.WriteByte(0x07);
  3879. fs.WriteByte(0x05);
  3880. }
  3881. // seek within file and not beyond buffer size
  3882. // do not write anything
  3883. using (var fs = client.OpenWrite(remoteFile))
  3884. {
  3885. var newPosition = fs.Seek(offset: -2L, SeekOrigin.End);
  3886. Assert.AreEqual(1, newPosition);
  3887. Assert.AreEqual(1, fs.Position);
  3888. }
  3889. using (var fs = client.OpenRead(remoteFile))
  3890. {
  3891. Assert.AreEqual(3, fs.Length);
  3892. Assert.AreEqual(0x04, fs.ReadByte());
  3893. Assert.AreEqual(0x07, fs.ReadByte());
  3894. Assert.AreEqual(0x05, fs.ReadByte());
  3895. // Ensure we've reached end of the stream
  3896. Assert.AreEqual(-1, fs.ReadByte());
  3897. }
  3898. client.DeleteFile(remoteFile);
  3899. // buffer holding the data that we'll write to the file
  3900. var writeBuffer = GenerateRandom(size: (int)client.BufferSize + 200);
  3901. using (var fs = client.OpenWrite(remoteFile))
  3902. {
  3903. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3904. }
  3905. // seek within EOF and beyond buffer size
  3906. // do not write anything
  3907. using (var fs = client.OpenWrite(remoteFile))
  3908. {
  3909. var newPosition = fs.Seek(offset: -100L, SeekOrigin.End);
  3910. Assert.AreEqual(600, newPosition);
  3911. Assert.AreEqual(600, fs.Position);
  3912. }
  3913. using (var fs = client.OpenRead(remoteFile))
  3914. {
  3915. Assert.AreEqual(writeBuffer.Length, fs.Length);
  3916. var readBuffer = new byte[writeBuffer.Length];
  3917. fs.ReadExactly(readBuffer, offset: 0, readBuffer.Length);
  3918. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  3919. // Ensure we've reached end of the stream
  3920. Assert.AreEqual(-1, fs.ReadByte());
  3921. }
  3922. client.DeleteFile(remoteFile);
  3923. // seek within EOF and within buffer size
  3924. // write less bytes than buffer size
  3925. using (var fs = client.OpenWrite(remoteFile))
  3926. {
  3927. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3928. var newPosition = fs.Seek(offset: -3, SeekOrigin.End);
  3929. Assert.AreEqual(697, newPosition);
  3930. Assert.AreEqual(697, fs.Position);
  3931. fs.WriteByte(0x01);
  3932. fs.WriteByte(0x05);
  3933. fs.WriteByte(0x04);
  3934. fs.WriteByte(0x07);
  3935. }
  3936. using (var fs = client.OpenRead(remoteFile))
  3937. {
  3938. Assert.AreEqual(writeBuffer.Length + 1, fs.Length);
  3939. var readBuffer = new byte[writeBuffer.Length - 3];
  3940. fs.ReadExactly(readBuffer, offset: 0, readBuffer.Length);
  3941. CollectionAssert.AreEqual(writeBuffer.Take(readBuffer.Length), readBuffer);
  3942. Assert.AreEqual(0x01, fs.ReadByte());
  3943. Assert.AreEqual(0x05, fs.ReadByte());
  3944. Assert.AreEqual(0x04, fs.ReadByte());
  3945. Assert.AreEqual(0x07, fs.ReadByte());
  3946. // Ensure we've reached end of the stream
  3947. Assert.AreEqual(-1, fs.ReadByte());
  3948. }
  3949. client.DeleteFile(remoteFile);
  3950. // buffer holding the data that we'll write to the file
  3951. writeBuffer = GenerateRandom(size: (int)client.BufferSize * 4);
  3952. // seek within EOF and beyond buffer size
  3953. // write less bytes than buffer size
  3954. using (var fs = client.OpenWrite(remoteFile))
  3955. {
  3956. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  3957. var newPosition = fs.Seek(offset: -(client.BufferSize * 2), SeekOrigin.End);
  3958. Assert.AreEqual(1000, newPosition);
  3959. Assert.AreEqual(1000, fs.Position);
  3960. fs.WriteByte(0x01);
  3961. fs.WriteByte(0x05);
  3962. fs.WriteByte(0x04);
  3963. fs.WriteByte(0x07);
  3964. }
  3965. using (var fs = client.OpenRead(remoteFile))
  3966. {
  3967. Assert.AreEqual(writeBuffer.Length, fs.Length);
  3968. // First part of file should not have been touched
  3969. var readBuffer = new byte[(int)client.BufferSize * 2];
  3970. fs.ReadExactly(readBuffer, offset: 0, readBuffer.Length);
  3971. CollectionAssert.AreEqual(writeBuffer.Take(readBuffer.Length), readBuffer);
  3972. // Check part that should have been updated
  3973. Assert.AreEqual(0x01, fs.ReadByte());
  3974. Assert.AreEqual(0x05, fs.ReadByte());
  3975. Assert.AreEqual(0x04, fs.ReadByte());
  3976. Assert.AreEqual(0x07, fs.ReadByte());
  3977. // Remaining bytes should not have been touched
  3978. readBuffer = new byte[((int)client.BufferSize * 2) - 4];
  3979. fs.ReadExactly(readBuffer, offset: 0, readBuffer.Length);
  3980. CollectionAssert.AreEqual(
  3981. writeBuffer.Skip(((int)client.BufferSize * 2) + 4).Take(readBuffer.Length).ToArray(),
  3982. readBuffer);
  3983. // Ensure we've reached end of the stream
  3984. Assert.AreEqual(-1, fs.ReadByte());
  3985. }
  3986. }
  3987. finally
  3988. {
  3989. if (client.Exists(remoteFile))
  3990. {
  3991. client.DeleteFile(remoteFile);
  3992. }
  3993. }
  3994. }
  3995. }
  3996. /// https://github.com/sshnet/SSH.NET/issues/253
  3997. [TestMethod]
  3998. public void Sftp_SftpFileStream_Seek_Issue253()
  3999. {
  4000. var buf = Encoding.UTF8.GetBytes("123456");
  4001. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4002. {
  4003. client.Connect();
  4004. var remoteFile = GenerateUniqueRemoteFileName();
  4005. if (client.Exists(remoteFile))
  4006. {
  4007. client.DeleteFile(remoteFile);
  4008. }
  4009. try
  4010. {
  4011. using (var ws = client.OpenWrite(remoteFile))
  4012. {
  4013. ws.Write(buf, offset: 0, count: 3);
  4014. }
  4015. using (var ws = client.OpenWrite(remoteFile))
  4016. {
  4017. var newPosition = ws.Seek(offset: 3, SeekOrigin.Begin);
  4018. Assert.AreEqual(3, newPosition);
  4019. Assert.AreEqual(3, ws.Position);
  4020. ws.Write(buf, 3, 3);
  4021. }
  4022. var actual = client.ReadAllText(remoteFile, Encoding.UTF8);
  4023. Assert.AreEqual("123456", actual);
  4024. }
  4025. finally
  4026. {
  4027. if (client.Exists(remoteFile))
  4028. {
  4029. client.DeleteFile(remoteFile);
  4030. }
  4031. }
  4032. }
  4033. }
  4034. [TestMethod]
  4035. public void Sftp_SftpFileStream_Seek_WithinReadBuffer()
  4036. {
  4037. var originalContent = GenerateRandom(size: 800);
  4038. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4039. {
  4040. client.BufferSize = 500;
  4041. client.Connect();
  4042. var remoteFile = GenerateUniqueRemoteFileName();
  4043. if (client.Exists(remoteFile))
  4044. {
  4045. client.DeleteFile(remoteFile);
  4046. }
  4047. try
  4048. {
  4049. using (var fs = client.OpenWrite(remoteFile))
  4050. {
  4051. fs.Write(originalContent, offset: 0, originalContent.Length);
  4052. }
  4053. using (var fs = client.OpenRead(remoteFile))
  4054. {
  4055. var readBuffer = new byte[200];
  4056. fs.ReadExactly(readBuffer, offset: 0, readBuffer.Length);
  4057. var newPosition = fs.Seek(offset: 3L, SeekOrigin.Begin);
  4058. Assert.AreEqual(3L, newPosition);
  4059. Assert.AreEqual(3L, fs.Position);
  4060. }
  4061. client.DeleteFile(remoteFile);
  4062. #region Seek beyond EOF and beyond buffer size do not write anything
  4063. // create single-byte file
  4064. using (var fs = client.OpenWrite(remoteFile))
  4065. {
  4066. fs.WriteByte(0x04);
  4067. }
  4068. using (var fs = client.OpenRead(remoteFile))
  4069. {
  4070. Assert.AreEqual(1, fs.Length);
  4071. Assert.AreEqual(0x04, fs.ReadByte());
  4072. // Ensure we've reached end of the stream
  4073. Assert.AreEqual(-1, fs.ReadByte());
  4074. }
  4075. using (var fs = client.OpenWrite(remoteFile))
  4076. {
  4077. var newPosition = fs.Seek(offset: 700L, SeekOrigin.Begin);
  4078. Assert.AreEqual(700L, newPosition);
  4079. Assert.AreEqual(700L, fs.Position);
  4080. }
  4081. using (var fs = client.OpenRead(remoteFile))
  4082. {
  4083. Assert.AreEqual(1, fs.Length);
  4084. Assert.AreEqual(0x04, fs.ReadByte());
  4085. // Ensure we've reached end of the stream
  4086. Assert.AreEqual(-1, fs.ReadByte());
  4087. }
  4088. client.DeleteFile(remoteFile);
  4089. #endregion Seek beyond EOF and beyond buffer size do not write anything
  4090. #region Seek beyond EOF but not beyond buffer size and write less bytes than buffer size
  4091. // create single-byte file
  4092. using (var fs = client.OpenWrite(remoteFile))
  4093. {
  4094. fs.WriteByte(0x04);
  4095. }
  4096. var seekOffset = 3L;
  4097. var writeBuffer = GenerateRandom(size: 7);
  4098. using (var fs = client.OpenWrite(remoteFile))
  4099. {
  4100. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  4101. Assert.AreEqual(seekOffset, newPosition);
  4102. Assert.AreEqual(seekOffset, fs.Position);
  4103. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4104. }
  4105. using (var fs = client.OpenRead(remoteFile))
  4106. {
  4107. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  4108. Assert.AreEqual(0x04, fs.ReadByte());
  4109. var soughtOverReadBuffer = new byte[seekOffset - 1];
  4110. fs.ReadExactly(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length);
  4111. CollectionAssert.AreEqual(new byte[soughtOverReadBuffer.Length], soughtOverReadBuffer);
  4112. var readBuffer = new byte[writeBuffer.Length];
  4113. fs.ReadExactly(readBuffer, offset: 0, readBuffer.Length);
  4114. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  4115. // Ensure we've reached end of the stream
  4116. Assert.AreEqual(-1, fs.ReadByte());
  4117. }
  4118. client.DeleteFile(remoteFile);
  4119. #endregion Seek beyond EOF but not beyond buffer size and write less bytes than buffer size
  4120. #region Seek beyond EOF and beyond buffer size and write less bytes than buffer size
  4121. // create single-byte file
  4122. using (var fs = client.OpenWrite(remoteFile))
  4123. {
  4124. fs.WriteByte(0x04);
  4125. }
  4126. seekOffset = 700L;
  4127. writeBuffer = GenerateRandom(size: 4);
  4128. using (var fs = client.OpenWrite(remoteFile))
  4129. {
  4130. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  4131. Assert.AreEqual(seekOffset, newPosition);
  4132. Assert.AreEqual(seekOffset, fs.Position);
  4133. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4134. }
  4135. using (var fs = client.OpenRead(remoteFile))
  4136. {
  4137. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  4138. Assert.AreEqual(0x04, fs.ReadByte());
  4139. var soughtOverReadBuffer = new byte[seekOffset - 1];
  4140. fs.ReadExactly(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length);
  4141. CollectionAssert.AreEqual(new byte[soughtOverReadBuffer.Length], soughtOverReadBuffer);
  4142. var readBuffer = new byte[writeBuffer.Length];
  4143. fs.ReadExactly(readBuffer, offset: 0, readBuffer.Length);
  4144. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  4145. // Ensure we've reached end of the stream
  4146. Assert.AreEqual(-1, fs.ReadByte());
  4147. }
  4148. client.DeleteFile(remoteFile);
  4149. #endregion Seek beyond EOF and beyond buffer size and write less bytes than buffer size
  4150. #region Seek beyond EOF but not beyond buffer size and write more bytes than buffer size
  4151. // create single-byte file
  4152. using (var fs = client.OpenWrite(remoteFile))
  4153. {
  4154. fs.WriteByte(0x04);
  4155. }
  4156. seekOffset = 3L;
  4157. writeBuffer = GenerateRandom(size: 600);
  4158. using (var fs = client.OpenWrite(remoteFile))
  4159. {
  4160. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  4161. Assert.AreEqual(seekOffset, newPosition);
  4162. Assert.AreEqual(seekOffset, fs.Position);
  4163. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4164. }
  4165. using (var fs = client.OpenRead(remoteFile))
  4166. {
  4167. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  4168. Assert.AreEqual(0x04, fs.ReadByte());
  4169. Assert.AreEqual(0x00, fs.ReadByte());
  4170. Assert.AreEqual(0x00, fs.ReadByte());
  4171. var readBuffer = new byte[writeBuffer.Length];
  4172. fs.ReadExactly(readBuffer, offset: 0, readBuffer.Length);
  4173. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  4174. // Ensure we've reached end of the stream
  4175. Assert.AreEqual(-1, fs.ReadByte());
  4176. }
  4177. client.DeleteFile(remoteFile);
  4178. #endregion Seek beyond EOF but not beyond buffer size and write more bytes than buffer size
  4179. #region Seek beyond EOF and beyond buffer size and write more bytes than buffer size
  4180. // create single-byte file
  4181. using (var fs = client.OpenWrite(remoteFile))
  4182. {
  4183. fs.WriteByte(0x04);
  4184. }
  4185. seekOffset = 550L;
  4186. writeBuffer = GenerateRandom(size: 600);
  4187. using (var fs = client.OpenWrite(remoteFile))
  4188. {
  4189. var newPosition = fs.Seek(seekOffset, SeekOrigin.Begin);
  4190. Assert.AreEqual(seekOffset, newPosition);
  4191. Assert.AreEqual(seekOffset, fs.Position);
  4192. fs.Write(writeBuffer, offset: 0, writeBuffer.Length);
  4193. }
  4194. using (var fs = client.OpenRead(remoteFile))
  4195. {
  4196. Assert.AreEqual(seekOffset + writeBuffer.Length, fs.Length);
  4197. Assert.AreEqual(0x04, fs.ReadByte());
  4198. var soughtOverReadBuffer = new byte[seekOffset - 1];
  4199. fs.ReadExactly(soughtOverReadBuffer, offset: 0, soughtOverReadBuffer.Length);
  4200. CollectionAssert.AreEqual(new byte[seekOffset - 1], soughtOverReadBuffer);
  4201. var readBuffer = new byte[writeBuffer.Length];
  4202. fs.ReadExactly(readBuffer, offset: 0, readBuffer.Length);
  4203. CollectionAssert.AreEqual(writeBuffer, readBuffer);
  4204. // Ensure we've reached end of the stream
  4205. Assert.AreEqual(-1, fs.ReadByte());
  4206. }
  4207. client.DeleteFile(remoteFile);
  4208. #endregion Seek beyond EOF and beyond buffer size and write more bytes than buffer size
  4209. }
  4210. finally
  4211. {
  4212. if (client.Exists(remoteFile))
  4213. {
  4214. client.DeleteFile(remoteFile);
  4215. }
  4216. }
  4217. }
  4218. }
  4219. [TestMethod]
  4220. public void Sftp_SftpFileStream_SetLength_FileDoesNotExist()
  4221. {
  4222. var size = new Random().Next(500, 5000);
  4223. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4224. {
  4225. client.Connect();
  4226. var remoteFile = GenerateUniqueRemoteFileName();
  4227. if (client.Exists(remoteFile))
  4228. {
  4229. client.DeleteFile(remoteFile);
  4230. }
  4231. try
  4232. {
  4233. using (var s = client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  4234. {
  4235. s.SetLength(size);
  4236. }
  4237. Assert.IsTrue(client.Exists(remoteFile));
  4238. var attributes = client.GetAttributes(remoteFile);
  4239. Assert.IsTrue(attributes.IsRegularFile);
  4240. Assert.AreEqual(size, attributes.Size);
  4241. using (var downloaded = new MemoryStream())
  4242. {
  4243. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4244. downloaded.Position = 0;
  4245. Assert.AreEqual(CreateHash(new byte[size]), CreateHash(downloaded));
  4246. }
  4247. }
  4248. finally
  4249. {
  4250. if (client.Exists(remoteFile))
  4251. {
  4252. client.DeleteFile(remoteFile);
  4253. }
  4254. }
  4255. }
  4256. }
  4257. [TestMethod]
  4258. public void Sftp_Open_Append_Write_ExistingFile()
  4259. {
  4260. const int fileSize = 5 * 1024;
  4261. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4262. using (var input = CreateMemoryStream(fileSize))
  4263. {
  4264. input.Position = 0;
  4265. client.Connect();
  4266. var remoteFile = GenerateUniqueRemoteFileName();
  4267. if (client.Exists(remoteFile))
  4268. {
  4269. client.DeleteFile(remoteFile);
  4270. }
  4271. try
  4272. {
  4273. client.UploadFile(input, remoteFile);
  4274. using (var s = client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  4275. {
  4276. Assert.IsFalse(s.CanRead);
  4277. Assert.IsTrue(s.CanWrite);
  4278. var buffer = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4279. s.Write(buffer, offset: 0, buffer.Length);
  4280. input.Write(buffer, offset: 0, buffer.Length);
  4281. }
  4282. using (var downloaded = new MemoryStream())
  4283. {
  4284. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4285. input.Position = 0;
  4286. downloaded.Position = 0;
  4287. Assert.AreEqual(CreateHash(input), CreateHash(downloaded));
  4288. }
  4289. }
  4290. finally
  4291. {
  4292. if (client.Exists(remoteFile))
  4293. {
  4294. client.DeleteFile(remoteFile);
  4295. }
  4296. }
  4297. }
  4298. }
  4299. [TestMethod]
  4300. public void Sftp_Open_Append_Write_FileDoesNotExist()
  4301. {
  4302. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4303. {
  4304. client.Connect();
  4305. var remoteFile = GenerateUniqueRemoteFileName();
  4306. if (client.Exists(remoteFile))
  4307. {
  4308. client.DeleteFile(remoteFile);
  4309. }
  4310. try
  4311. {
  4312. #region Verify if merely opening the file for append creates a zero-byte file
  4313. using (client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  4314. {
  4315. }
  4316. Assert.IsTrue(client.Exists(remoteFile));
  4317. var attributes = client.GetAttributes(remoteFile);
  4318. Assert.IsTrue(attributes.IsRegularFile);
  4319. Assert.AreEqual(0L, attributes.Size);
  4320. #endregion Verify if merely opening the file for append creates it
  4321. client.DeleteFile(remoteFile);
  4322. #region Verify if content is actually written to the file
  4323. var content = GenerateRandom(size: 100);
  4324. using (var s = client.Open(remoteFile, FileMode.Append, FileAccess.Write))
  4325. {
  4326. s.Write(content, offset: 0, content.Length);
  4327. }
  4328. using (var downloaded = new MemoryStream())
  4329. {
  4330. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4331. downloaded.Position = 0;
  4332. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4333. }
  4334. #endregion Verify if content is actually written to the file
  4335. }
  4336. finally
  4337. {
  4338. if (client.Exists(remoteFile))
  4339. {
  4340. client.DeleteFile(remoteFile);
  4341. }
  4342. }
  4343. }
  4344. }
  4345. [TestMethod]
  4346. public void Sftp_Open_PathAndMode_ModeIsCreate_FileDoesNotExist()
  4347. {
  4348. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4349. {
  4350. client.Connect();
  4351. var remoteFile = GenerateUniqueRemoteFileName();
  4352. if (client.Exists(remoteFile))
  4353. {
  4354. client.DeleteFile(remoteFile);
  4355. }
  4356. try
  4357. {
  4358. #region Verify if merely opening the file for create creates a zero-byte file
  4359. using (client.Open(remoteFile, FileMode.Create))
  4360. {
  4361. }
  4362. Assert.IsTrue(client.Exists(remoteFile));
  4363. var attributes = client.GetAttributes(remoteFile);
  4364. Assert.IsTrue(attributes.IsRegularFile);
  4365. Assert.AreEqual(0L, attributes.Size);
  4366. #endregion Verify if merely opening the file for create creates a zero-byte file
  4367. client.DeleteFile(remoteFile);
  4368. #region Verify if content is actually written to the file
  4369. var content = GenerateRandom(size: 100);
  4370. using (var s = client.Open(remoteFile, FileMode.Create))
  4371. {
  4372. Assert.IsTrue(s.CanRead);
  4373. Assert.IsTrue(s.CanWrite);
  4374. s.Write(content, offset: 0, content.Length);
  4375. }
  4376. using (var downloaded = new MemoryStream())
  4377. {
  4378. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4379. downloaded.Position = 0;
  4380. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4381. }
  4382. #endregion Verify if content is actually written to the file
  4383. }
  4384. finally
  4385. {
  4386. if (client.Exists(remoteFile))
  4387. {
  4388. client.DeleteFile(remoteFile);
  4389. }
  4390. }
  4391. }
  4392. }
  4393. [TestMethod]
  4394. public void Sftp_Open_PathAndMode_ModeIsCreate_ExistingFile()
  4395. {
  4396. const int fileSize = 5 * 1024;
  4397. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4398. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4399. using (var input = CreateMemoryStream(fileSize))
  4400. {
  4401. client.Connect();
  4402. var remoteFile = GenerateUniqueRemoteFileName();
  4403. if (client.Exists(remoteFile))
  4404. {
  4405. client.DeleteFile(remoteFile);
  4406. }
  4407. try
  4408. {
  4409. input.Position = 0;
  4410. client.UploadFile(input, remoteFile);
  4411. using (var stream = client.Open(remoteFile, FileMode.Create))
  4412. {
  4413. // Verify if merely opening the file for create overwrites the file
  4414. var attributes = client.GetAttributes(remoteFile);
  4415. Assert.IsTrue(attributes.IsRegularFile);
  4416. Assert.AreEqual(0L, attributes.Size);
  4417. stream.Write(newContent, offset: 0, newContent.Length);
  4418. stream.Position = 0;
  4419. Assert.AreEqual(CreateHash(newContent), CreateHash(stream));
  4420. }
  4421. }
  4422. finally
  4423. {
  4424. if (client.Exists(remoteFile))
  4425. {
  4426. client.DeleteFile(remoteFile);
  4427. }
  4428. }
  4429. }
  4430. }
  4431. [TestMethod]
  4432. public void Sftp_Open_PathAndModeAndAccess_ModeIsCreate_AccessIsReadWrite_FileDoesNotExist()
  4433. {
  4434. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4435. {
  4436. client.Connect();
  4437. var remoteFile = GenerateUniqueRemoteFileName();
  4438. if (client.Exists(remoteFile))
  4439. {
  4440. client.DeleteFile(remoteFile);
  4441. }
  4442. try
  4443. {
  4444. #region Verify if merely opening the file for create creates a zero-byte file
  4445. using (client.Open(remoteFile, FileMode.Create, FileAccess.ReadWrite))
  4446. {
  4447. }
  4448. Assert.IsTrue(client.Exists(remoteFile));
  4449. var attributes = client.GetAttributes(remoteFile);
  4450. Assert.IsTrue(attributes.IsRegularFile);
  4451. Assert.AreEqual(0L, attributes.Size);
  4452. #endregion Verify if merely opening the file for create creates a zero-byte file
  4453. client.DeleteFile(remoteFile);
  4454. #region Verify if content is actually written to the file
  4455. var content = GenerateRandom(size: 100);
  4456. using (var s = client.Open(remoteFile, FileMode.Create, FileAccess.ReadWrite))
  4457. {
  4458. s.Write(content, offset: 0, content.Length);
  4459. }
  4460. using (var downloaded = new MemoryStream())
  4461. {
  4462. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4463. downloaded.Position = 0;
  4464. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4465. }
  4466. #endregion Verify if content is actually written to the file
  4467. }
  4468. finally
  4469. {
  4470. if (client.Exists(remoteFile))
  4471. {
  4472. client.DeleteFile(remoteFile);
  4473. }
  4474. }
  4475. }
  4476. }
  4477. [TestMethod]
  4478. public void Sftp_Open_PathAndModeAndAccess_ModeIsCreate_AccessIsReadWrite_ExistingFile()
  4479. {
  4480. const int fileSize = 5 * 1024;
  4481. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4482. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4483. using (var input = CreateMemoryStream(fileSize))
  4484. {
  4485. client.Connect();
  4486. var remoteFile = GenerateUniqueRemoteFileName();
  4487. if (client.Exists(remoteFile))
  4488. {
  4489. client.DeleteFile(remoteFile);
  4490. }
  4491. try
  4492. {
  4493. input.Position = 0;
  4494. client.UploadFile(input, remoteFile);
  4495. using (var stream = client.Open(remoteFile, FileMode.Create, FileAccess.ReadWrite))
  4496. {
  4497. // Verify if merely opening the file for create overwrites the file
  4498. var attributes = client.GetAttributes(remoteFile);
  4499. Assert.IsTrue(attributes.IsRegularFile);
  4500. Assert.AreEqual(0L, attributes.Size);
  4501. stream.Write(newContent, offset: 0, newContent.Length);
  4502. stream.Position = 0;
  4503. Assert.AreEqual(CreateHash(newContent), CreateHash(stream));
  4504. }
  4505. }
  4506. finally
  4507. {
  4508. if (client.Exists(remoteFile))
  4509. {
  4510. client.DeleteFile(remoteFile);
  4511. }
  4512. }
  4513. }
  4514. }
  4515. [TestMethod]
  4516. public void Sftp_Open_PathAndModeAndAccess_ModeIsCreate_AccessIsWrite_ExistingFile()
  4517. {
  4518. // use new content that contains less bytes than original content to
  4519. // verify whether file is first truncated
  4520. var originalContent = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4521. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4522. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4523. {
  4524. client.Connect();
  4525. var remoteFile = GenerateUniqueRemoteFileName();
  4526. if (client.Exists(remoteFile))
  4527. {
  4528. client.DeleteFile(remoteFile);
  4529. }
  4530. try
  4531. {
  4532. client.WriteAllBytes(remoteFile, originalContent);
  4533. using (var s = client.Open(remoteFile, FileMode.Create, FileAccess.Write))
  4534. {
  4535. s.Write(newContent, offset: 0, newContent.Length);
  4536. }
  4537. using (var downloaded = new MemoryStream())
  4538. {
  4539. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4540. downloaded.Position = 0;
  4541. Assert.AreEqual(CreateHash(newContent), CreateHash(downloaded));
  4542. }
  4543. }
  4544. finally
  4545. {
  4546. if (client.Exists(remoteFile))
  4547. {
  4548. client.DeleteFile(remoteFile);
  4549. }
  4550. }
  4551. }
  4552. }
  4553. [TestMethod]
  4554. public void Sftp_Open_PathAndModeAndAccess_ModeIsCreate_AccessIsWrite_FileDoesNotExist()
  4555. {
  4556. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4557. {
  4558. client.Connect();
  4559. var remoteFile = GenerateUniqueRemoteFileName();
  4560. if (client.Exists(remoteFile))
  4561. {
  4562. client.DeleteFile(remoteFile);
  4563. }
  4564. try
  4565. {
  4566. #region Verify if merely opening the file for create creates a zero-byte file
  4567. using (client.Open(remoteFile, FileMode.Create, FileAccess.Write))
  4568. {
  4569. }
  4570. Assert.IsTrue(client.Exists(remoteFile));
  4571. var attributes = client.GetAttributes(remoteFile);
  4572. Assert.IsTrue(attributes.IsRegularFile);
  4573. Assert.AreEqual(0L, attributes.Size);
  4574. #endregion Verify if merely opening the file for create creates a zero-byte file
  4575. client.DeleteFile(remoteFile);
  4576. #region Verify if content is actually written to the file
  4577. var content = GenerateRandom(size: 100);
  4578. using (var s = client.Open(remoteFile, FileMode.Create, FileAccess.Write))
  4579. {
  4580. s.Write(content, offset: 0, content.Length);
  4581. }
  4582. using (var downloaded = new MemoryStream())
  4583. {
  4584. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4585. downloaded.Position = 0;
  4586. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4587. }
  4588. #endregion Verify if content is actually written to the file
  4589. }
  4590. finally
  4591. {
  4592. if (client.Exists(remoteFile))
  4593. {
  4594. client.DeleteFile(remoteFile);
  4595. }
  4596. }
  4597. }
  4598. }
  4599. [TestMethod]
  4600. public void Sftp_Open_CreateNew_Write_ExistingFile()
  4601. {
  4602. const int fileSize = 5 * 1024;
  4603. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4604. using (var input = CreateMemoryStream(fileSize))
  4605. {
  4606. client.Connect();
  4607. var remoteFile = GenerateUniqueRemoteFileName();
  4608. if (client.Exists(remoteFile))
  4609. {
  4610. client.DeleteFile(remoteFile);
  4611. }
  4612. input.Position = 0;
  4613. try
  4614. {
  4615. client.UploadFile(input, remoteFile);
  4616. Stream stream = null;
  4617. try
  4618. {
  4619. stream = client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write);
  4620. Assert.Fail();
  4621. }
  4622. catch (SshException)
  4623. {
  4624. }
  4625. finally
  4626. {
  4627. stream?.Dispose();
  4628. }
  4629. // Verify that the file was not modified
  4630. using (var downloaded = new MemoryStream())
  4631. {
  4632. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4633. input.Position = 0;
  4634. downloaded.Position = 0;
  4635. Assert.AreEqual(CreateHash(input), CreateHash(downloaded));
  4636. }
  4637. }
  4638. finally
  4639. {
  4640. if (client.Exists(remoteFile))
  4641. {
  4642. client.DeleteFile(remoteFile);
  4643. }
  4644. }
  4645. }
  4646. }
  4647. [TestMethod]
  4648. public void Sftp_Open_CreateNew_Write_FileDoesNotExist()
  4649. {
  4650. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4651. {
  4652. client.Connect();
  4653. var remoteFile = GenerateUniqueRemoteFileName();
  4654. if (client.Exists(remoteFile))
  4655. {
  4656. client.DeleteFile(remoteFile);
  4657. }
  4658. try
  4659. {
  4660. #region Verify if merely opening the file creates a zero-byte file
  4661. using (client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write))
  4662. {
  4663. }
  4664. Assert.IsTrue(client.Exists(remoteFile));
  4665. var attributes = client.GetAttributes(remoteFile);
  4666. Assert.IsTrue(attributes.IsRegularFile);
  4667. Assert.AreEqual(0L, attributes.Size);
  4668. #endregion Verify if merely opening the file creates it
  4669. client.DeleteFile(remoteFile);
  4670. #region Verify if content is actually written to the file
  4671. var content = GenerateRandom(size: 100);
  4672. using (var s = client.Open(remoteFile, FileMode.CreateNew, FileAccess.Write))
  4673. {
  4674. s.Write(content, offset: 0, content.Length);
  4675. }
  4676. using (var downloaded = new MemoryStream())
  4677. {
  4678. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4679. downloaded.Position = 0;
  4680. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4681. }
  4682. #endregion Verify if content is actually written to the file
  4683. }
  4684. finally
  4685. {
  4686. if (client.Exists(remoteFile))
  4687. {
  4688. client.DeleteFile(remoteFile);
  4689. }
  4690. }
  4691. }
  4692. }
  4693. [TestMethod]
  4694. public void Sftp_Open_Open_Write_ExistingFile()
  4695. {
  4696. // use new content that contains less bytes than original content to
  4697. // verify whether file is first truncated
  4698. var originalContent = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4699. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4700. var expectedContent = new byte[] { 0x07, 0x03, 0x02, 0x0b, 0x04 };
  4701. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4702. {
  4703. client.Connect();
  4704. var remoteFile = GenerateUniqueRemoteFileName();
  4705. if (client.Exists(remoteFile))
  4706. {
  4707. client.DeleteFile(remoteFile);
  4708. }
  4709. try
  4710. {
  4711. client.WriteAllBytes(remoteFile, originalContent);
  4712. using (var s = client.Open(remoteFile, FileMode.Open, FileAccess.Write))
  4713. {
  4714. s.Write(newContent, offset: 0, newContent.Length);
  4715. }
  4716. using (var downloaded = new MemoryStream())
  4717. {
  4718. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4719. downloaded.Position = 0;
  4720. Assert.AreEqual(CreateHash(expectedContent), CreateHash(downloaded));
  4721. }
  4722. }
  4723. finally
  4724. {
  4725. if (client.Exists(remoteFile))
  4726. {
  4727. client.DeleteFile(remoteFile);
  4728. }
  4729. }
  4730. }
  4731. }
  4732. [TestMethod]
  4733. public void Sftp_Open_Open_Write_FileDoesNotExist()
  4734. {
  4735. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4736. {
  4737. client.Connect();
  4738. var remoteFile = GenerateUniqueRemoteFileName();
  4739. if (client.Exists(remoteFile))
  4740. {
  4741. client.DeleteFile(remoteFile);
  4742. }
  4743. try
  4744. {
  4745. Stream stream = null;
  4746. try
  4747. {
  4748. stream = client.Open(remoteFile, FileMode.Open, FileAccess.Write);
  4749. Assert.Fail();
  4750. }
  4751. catch (SshException)
  4752. {
  4753. }
  4754. finally
  4755. {
  4756. stream?.Dispose();
  4757. }
  4758. Assert.IsFalse(client.Exists(remoteFile));
  4759. }
  4760. finally
  4761. {
  4762. if (client.Exists(remoteFile))
  4763. {
  4764. client.DeleteFile(remoteFile);
  4765. }
  4766. }
  4767. }
  4768. }
  4769. [TestMethod]
  4770. public void Sftp_Open_OpenOrCreate_Write_ExistingFile()
  4771. {
  4772. // use new content that contains less bytes than original content to
  4773. // verify whether file is first truncated
  4774. var originalContent = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4775. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4776. var expectedContent = new byte[] { 0x07, 0x03, 0x02, 0x0b, 0x04 };
  4777. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4778. {
  4779. client.Connect();
  4780. var remoteFile = GenerateUniqueRemoteFileName();
  4781. if (client.Exists(remoteFile))
  4782. {
  4783. client.DeleteFile(remoteFile);
  4784. }
  4785. try
  4786. {
  4787. client.WriteAllBytes(remoteFile, originalContent);
  4788. using (var s = client.Open(remoteFile, FileMode.OpenOrCreate, FileAccess.Write))
  4789. {
  4790. s.Write(newContent, offset: 0, newContent.Length);
  4791. }
  4792. using (var downloaded = new MemoryStream())
  4793. {
  4794. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4795. downloaded.Position = 0;
  4796. Assert.AreEqual(CreateHash(expectedContent), CreateHash(downloaded));
  4797. }
  4798. }
  4799. finally
  4800. {
  4801. if (client.Exists(remoteFile))
  4802. {
  4803. client.DeleteFile(remoteFile);
  4804. }
  4805. }
  4806. }
  4807. }
  4808. [TestMethod]
  4809. public void Sftp_Open_OpenOrCreate_Write_FileDoesNotExist()
  4810. {
  4811. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4812. {
  4813. client.Connect();
  4814. var remoteFile = GenerateUniqueRemoteFileName();
  4815. if (client.Exists(remoteFile))
  4816. {
  4817. client.DeleteFile(remoteFile);
  4818. }
  4819. try
  4820. {
  4821. #region Verify if merely opening the file creates a zero-byte file
  4822. using (client.Open(remoteFile, FileMode.OpenOrCreate, FileAccess.Write))
  4823. {
  4824. }
  4825. Assert.IsTrue(client.Exists(remoteFile));
  4826. var attributes = client.GetAttributes(remoteFile);
  4827. Assert.IsTrue(attributes.IsRegularFile);
  4828. Assert.AreEqual(0L, attributes.Size);
  4829. #endregion Verify if merely opening the file creates it
  4830. client.DeleteFile(remoteFile);
  4831. #region Verify if content is actually written to the file
  4832. var content = GenerateRandom(size: 100);
  4833. using (var s = client.Open(remoteFile, FileMode.OpenOrCreate, FileAccess.Write))
  4834. {
  4835. s.Write(content, offset: 0, content.Length);
  4836. }
  4837. using (var downloaded = new MemoryStream())
  4838. {
  4839. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4840. downloaded.Position = 0;
  4841. Assert.AreEqual(CreateHash(content), CreateHash(downloaded));
  4842. }
  4843. #endregion Verify if content is actually written to the file
  4844. }
  4845. finally
  4846. {
  4847. if (client.Exists(remoteFile))
  4848. {
  4849. client.DeleteFile(remoteFile);
  4850. }
  4851. }
  4852. }
  4853. }
  4854. [TestMethod]
  4855. public void Sftp_Open_Truncate_Write_ExistingFile()
  4856. {
  4857. const int fileSize = 5 * 1024;
  4858. // use new content that contains less bytes than original content to
  4859. // verify whether file is first truncated
  4860. var originalContent = new byte[] { 0x05, 0x0f, 0x0d, 0x0a, 0x04 };
  4861. var newContent = new byte[] { 0x07, 0x03, 0x02, 0x0b };
  4862. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4863. using (var input = CreateMemoryStream(fileSize))
  4864. {
  4865. client.Connect();
  4866. var remoteFile = GenerateUniqueRemoteFileName();
  4867. if (client.Exists(remoteFile))
  4868. {
  4869. client.DeleteFile(remoteFile);
  4870. }
  4871. input.Position = 0;
  4872. try
  4873. {
  4874. client.WriteAllBytes(remoteFile, originalContent);
  4875. using (var s = client.Open(remoteFile, FileMode.Truncate, FileAccess.Write))
  4876. {
  4877. s.Write(newContent, offset: 0, newContent.Length);
  4878. }
  4879. using (var downloaded = new MemoryStream())
  4880. {
  4881. DownloadFileRandomMethod(client, remoteFile, downloaded);
  4882. input.Position = 0;
  4883. downloaded.Position = 0;
  4884. Assert.AreEqual(CreateHash(newContent), CreateHash(downloaded));
  4885. }
  4886. }
  4887. finally
  4888. {
  4889. if (client.Exists(remoteFile))
  4890. {
  4891. client.DeleteFile(remoteFile);
  4892. }
  4893. }
  4894. }
  4895. }
  4896. [TestMethod]
  4897. public void Sftp_Open_Truncate_Write_FileDoesNotExist()
  4898. {
  4899. using (var client = new SftpClient(_connectionInfoFactory.Create()))
  4900. {
  4901. client.Connect();
  4902. var remoteFile = GenerateUniqueRemoteFileName();
  4903. if (client.Exists(remoteFile))
  4904. {
  4905. client.DeleteFile(remoteFile);
  4906. }
  4907. try
  4908. {
  4909. Stream stream = null;
  4910. try
  4911. {
  4912. stream = client.Open(remoteFile, FileMode.Truncate, FileAccess.Write);
  4913. Assert.Fail();
  4914. }
  4915. catch (SshException)
  4916. {
  4917. }
  4918. Assert.IsFalse(client.Exists(remoteFile));
  4919. }
  4920. finally
  4921. {
  4922. if (client.Exists(remoteFile))
  4923. {
  4924. client.DeleteFile(remoteFile);
  4925. }
  4926. }
  4927. }
  4928. }
  4929. [TestMethod]
  4930. public void Sftp_SetLastAccessTime()
  4931. {
  4932. var testFilePath = "/home/sshnet/test-file.txt";
  4933. var testContent = "File";
  4934. using var client = new SftpClient(_connectionInfoFactory.Create());
  4935. client.Connect();
  4936. using var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(testContent));
  4937. client.UploadFile(fileStream, testFilePath);
  4938. try
  4939. {
  4940. var newTime = new DateTime(1986, 03, 15, 01, 02, 03, 123, DateTimeKind.Local);
  4941. client.SetLastAccessTime(testFilePath, newTime);
  4942. var time = client.GetLastAccessTime(testFilePath);
  4943. DateTimeAssert.AreEqual(newTime.TruncateToWholeSeconds(), time);
  4944. }
  4945. finally
  4946. {
  4947. client.DeleteFile(testFilePath);
  4948. }
  4949. }
  4950. [TestMethod]
  4951. public void Sftp_SetLastAccessTimeUtc()
  4952. {
  4953. var testFilePath = "/home/sshnet/test-file.txt";
  4954. var testContent = "File";
  4955. using var client = new SftpClient(_connectionInfoFactory.Create());
  4956. client.Connect();
  4957. using var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(testContent));
  4958. client.UploadFile(fileStream, testFilePath);
  4959. try
  4960. {
  4961. var newTime = new DateTime(1986, 03, 15, 01, 02, 03, 123, DateTimeKind.Utc);
  4962. client.SetLastAccessTimeUtc(testFilePath, newTime);
  4963. var time = client.GetLastAccessTimeUtc(testFilePath);
  4964. DateTimeAssert.AreEqual(newTime.TruncateToWholeSeconds(), time);
  4965. }
  4966. finally
  4967. {
  4968. client.DeleteFile(testFilePath);
  4969. }
  4970. }
  4971. [TestMethod]
  4972. public void Sftp_SetLastWriteTime()
  4973. {
  4974. var testFilePath = "/home/sshnet/test-file.txt";
  4975. var testContent = "File";
  4976. using var client = new SftpClient(_connectionInfoFactory.Create());
  4977. client.Connect();
  4978. using var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(testContent));
  4979. client.UploadFile(fileStream, testFilePath);
  4980. try
  4981. {
  4982. var newTime = new DateTime(1986, 03, 15, 01, 02, 03, 123, DateTimeKind.Local);
  4983. client.SetLastWriteTime(testFilePath, newTime);
  4984. var time = client.GetLastWriteTime(testFilePath);
  4985. DateTimeAssert.AreEqual(newTime.TruncateToWholeSeconds(), time);
  4986. }
  4987. finally
  4988. {
  4989. client.DeleteFile(testFilePath);
  4990. }
  4991. }
  4992. [TestMethod]
  4993. public void Sftp_SetLastWriteTimeUtc()
  4994. {
  4995. var testFilePath = "/home/sshnet/test-file.txt";
  4996. var testContent = "File";
  4997. using var client = new SftpClient(_connectionInfoFactory.Create());
  4998. client.Connect();
  4999. using var fileStream = new MemoryStream(Encoding.UTF8.GetBytes(testContent));
  5000. client.UploadFile(fileStream, testFilePath);
  5001. try
  5002. {
  5003. var newTime = new DateTime(1986, 03, 15, 01, 02, 03, 123, DateTimeKind.Utc);
  5004. client.SetLastWriteTimeUtc(testFilePath, newTime);
  5005. var time = client.GetLastWriteTimeUtc(testFilePath);
  5006. DateTimeAssert.AreEqual(newTime.TruncateToWholeSeconds(), time);
  5007. }
  5008. finally
  5009. {
  5010. client.DeleteFile(testFilePath);
  5011. }
  5012. }
  5013. [TestMethod]
  5014. public void Sftp_SftpFileStream_Fuzz()
  5015. {
  5016. const int OperationCount = 100;
  5017. const int MaxBufferSize = 1000;
  5018. const int MaxFileSize = 15_000;
  5019. int seed = Environment.TickCount;
  5020. Console.WriteLine("Using seed " + seed);
  5021. var random = new Random(seed);
  5022. using var client = new SftpClient(_connectionInfoFactory.Create())
  5023. {
  5024. BufferSize = 100
  5025. };
  5026. client.Connect();
  5027. // We will perform operations on an SftpFileStream and a local
  5028. // System.IO.FileStream, and check that the results are the same.
  5029. // This could use a MemoryStream for the local side, except for the
  5030. // fact that performing a 0-byte write at a position beyond the length
  5031. // of the MemoryStream causes its length to increase, which is not the
  5032. // case for FileStream. Since we've got 'FileStream' in the name, we
  5033. // check that we align with FileStream's behaviour.
  5034. string remoteFilePath = GenerateUniqueRemoteFileName();
  5035. string localFilePath = Path.GetTempFileName();
  5036. byte[] fileBytes = new byte[1024];
  5037. random.NextBytes(fileBytes);
  5038. File.WriteAllBytes(localFilePath, fileBytes);
  5039. client.WriteAllBytes(remoteFilePath, fileBytes);
  5040. try
  5041. {
  5042. using (var local = File.Open(localFilePath, FileMode.Open, FileAccess.ReadWrite))
  5043. using (var remote = client.Open(remoteFilePath, FileMode.Open, FileAccess.ReadWrite))
  5044. {
  5045. for (int i = 0; i < OperationCount; i++)
  5046. {
  5047. #pragma warning disable IDE0010 // Add missing cases
  5048. int op = random.Next(5);
  5049. switch (op)
  5050. {
  5051. case 0 when local.Length < MaxFileSize: // Write
  5052. {
  5053. var buffer = new byte[random.Next(0, MaxBufferSize)];
  5054. random.NextBytes(buffer);
  5055. int offset = random.Next(0, buffer.Length + 1);
  5056. int count = random.Next(0, buffer.Length - offset + 1);
  5057. remote.Write(buffer, offset, count);
  5058. local.Write(buffer, offset, count);
  5059. break;
  5060. }
  5061. case 1: // Read
  5062. {
  5063. var remoteBuffer = new byte[random.Next(0, MaxBufferSize)];
  5064. var localBuffer = new byte[remoteBuffer.Length];
  5065. int offset = random.Next(0, remoteBuffer.Length + 1);
  5066. int count = random.Next(0, remoteBuffer.Length - offset + 1);
  5067. int remoteRead = ReadExactly(remote, remoteBuffer, offset, count);
  5068. int localRead = ReadExactly(local, localBuffer, offset, count);
  5069. Assert.AreEqual(localRead, remoteRead);
  5070. CollectionAssert.AreEqual(localBuffer, remoteBuffer);
  5071. break;
  5072. }
  5073. case 2 when local.Length < MaxFileSize: // Seek
  5074. {
  5075. int position = (int)local.Position;
  5076. int length = (int)local.Length;
  5077. SeekOrigin origin = (SeekOrigin)random.Next(0, 3);
  5078. long offset = 0;
  5079. switch (origin)
  5080. {
  5081. case SeekOrigin.Begin:
  5082. offset = random.Next(0, length * 2);
  5083. break;
  5084. case SeekOrigin.Current:
  5085. offset = random.Next(-position, position);
  5086. break;
  5087. case SeekOrigin.End:
  5088. offset = random.Next(-length, length);
  5089. break;
  5090. }
  5091. long newPosRemote = remote.Seek(offset, origin);
  5092. long newPosLocal = local.Seek(offset, origin);
  5093. Assert.AreEqual(newPosLocal, newPosRemote);
  5094. Assert.AreEqual(local.Length, remote.Length);
  5095. break;
  5096. }
  5097. case 3: // SetLength
  5098. {
  5099. long newLength = random.Next(0, MaxFileSize);
  5100. remote.SetLength(newLength);
  5101. local.SetLength(newLength);
  5102. Assert.AreEqual(local.Length, remote.Length);
  5103. Assert.AreEqual(local.Position, remote.Position);
  5104. break;
  5105. }
  5106. case 4: // Flush
  5107. {
  5108. remote.Flush();
  5109. local.Flush();
  5110. break;
  5111. }
  5112. }
  5113. #pragma warning restore IDE0010 // Add missing cases
  5114. }
  5115. }
  5116. CollectionAssert.AreEqual(File.ReadAllBytes(localFilePath), client.ReadAllBytes(remoteFilePath));
  5117. }
  5118. finally
  5119. {
  5120. File.Delete(localFilePath);
  5121. if (client.Exists(remoteFilePath))
  5122. {
  5123. client.DeleteFile(remoteFilePath);
  5124. }
  5125. }
  5126. }
  5127. private static IEnumerable<object[]> GetSftpUploadFileFileStreamData()
  5128. {
  5129. yield return new object[] { 0 };
  5130. yield return new object[] { 5 * 1024 * 1024 };
  5131. }
  5132. private static Encoding GetRandomEncoding()
  5133. {
  5134. var random = new Random().Next(1, 4);
  5135. switch (random)
  5136. {
  5137. case 1:
  5138. return Encoding.Unicode;
  5139. case 2:
  5140. return Encoding.UTF8;
  5141. default:
  5142. Debug.Assert(random == 3);
  5143. return Encoding.UTF32;
  5144. }
  5145. }
  5146. private void DownloadFileRandomMethod(SftpClient client, string path, Stream output)
  5147. {
  5148. Console.Write($"Downloading '{path}'");
  5149. var random = new Random().Next(1, 7);
  5150. switch (random)
  5151. {
  5152. case 1:
  5153. Console.WriteLine($" with {nameof(SftpClient.DownloadFile)}");
  5154. client.DownloadFile(path, output);
  5155. break;
  5156. case 2:
  5157. Console.WriteLine($" with {nameof(SftpClient.DownloadFileAsync)}");
  5158. client.DownloadFileAsync(path, output).GetAwaiter().GetResult();
  5159. break;
  5160. case 3:
  5161. Console.WriteLine($" with {nameof(SftpClient.BeginDownloadFile)}");
  5162. client.EndDownloadFile(client.BeginDownloadFile(path, output));
  5163. break;
  5164. case 4:
  5165. Console.WriteLine($" with {nameof(SftpFileStream.CopyTo)}");
  5166. using (var fs = client.OpenRead(path))
  5167. {
  5168. fs.CopyTo(output);
  5169. }
  5170. break;
  5171. case 5:
  5172. Console.WriteLine($" with {nameof(SftpFileStream.CopyToAsync)}");
  5173. using (var fs = client.OpenAsync(path, FileMode.Open, FileAccess.Read, CancellationToken.None).GetAwaiter().GetResult())
  5174. {
  5175. fs.CopyToAsync(output).GetAwaiter().GetResult();
  5176. }
  5177. break;
  5178. default:
  5179. Debug.Assert(random == 6);
  5180. Console.WriteLine($" with {nameof(SftpClient.ReadAllBytes)}");
  5181. byte[] bytes = client.ReadAllBytes(path);
  5182. output.Write(bytes, 0, bytes.Length);
  5183. break;
  5184. }
  5185. }
  5186. private static byte[] GetBytesWithPreamble(string text, Encoding encoding)
  5187. {
  5188. var preamble = encoding.GetPreamble();
  5189. var textBytes = encoding.GetBytes(text);
  5190. if (preamble.Length != 0)
  5191. {
  5192. var textAndPreambleBytes = new byte[preamble.Length + textBytes.Length];
  5193. Buffer.BlockCopy(preamble, srcOffset: 0, textAndPreambleBytes, dstOffset: 0, preamble.Length);
  5194. Buffer.BlockCopy(textBytes, srcOffset: 0, textAndPreambleBytes, preamble.Length, textBytes.Length);
  5195. return textAndPreambleBytes;
  5196. }
  5197. return textBytes;
  5198. }
  5199. private static decimal CalculateTransferSpeed(long length, long elapsedMilliseconds)
  5200. {
  5201. return (length / 1024m) / (elapsedMilliseconds / 1000m);
  5202. }
  5203. /// <summary>
  5204. /// Similar to the netcore ReadExactly but without throwing on end of stream.
  5205. /// </summary>
  5206. private static int ReadExactly(Stream stream, byte[] buffer, int offset, int count)
  5207. {
  5208. int totalRead = 0;
  5209. while (totalRead < count)
  5210. {
  5211. int read = stream.Read(buffer, offset + totalRead, count - totalRead);
  5212. if (read == 0)
  5213. {
  5214. return totalRead;
  5215. }
  5216. totalRead += read;
  5217. }
  5218. return totalRead;
  5219. }
  5220. private static byte[] GenerateRandom(int size)
  5221. {
  5222. var random = new Random();
  5223. var randomContent = new byte[size];
  5224. random.NextBytes(randomContent);
  5225. return randomContent;
  5226. }
  5227. private static Stream CreateStreamWithContent(string content)
  5228. {
  5229. var memoryStream = new MemoryStream();
  5230. var sw = new StreamWriter(memoryStream, Encoding.ASCII, 1024);
  5231. sw.Write(content);
  5232. sw.Flush();
  5233. memoryStream.Position = 0;
  5234. return memoryStream;
  5235. }
  5236. private static string GenerateUniqueRemoteFileName()
  5237. {
  5238. return $"/home/sshnet/{Guid.NewGuid():D}";
  5239. }
  5240. }
  5241. }